如何在 Java 中決定自定義異常是受檢異常還是非受檢異常?
異常是在程式執行期間發生的錯誤(執行時錯誤)。當發生異常時,程式會突然終止,並且異常發生行之後的程式碼將不會執行。
使用者定義的異常
您可以在 Java 中建立自己的異常,這些異常被稱為使用者定義的異常或自定義異常。
要建立使用者定義的異常,請擴充套件上述類之一。要顯示訊息,請覆蓋 **toString()** 方法,或者透過以字串格式傳遞訊息來呼叫超類的帶引數建構函式。
MyException(String msg){
super(msg);
}
Or,
public String toString(){
return " MyException [Message of your exception]";
}然後,在其他需要引發此異常的類中,建立已建立的自定義異常類的物件,並使用 throw 關鍵字丟擲異常。
MyException ex = new MyException ();
If(condition……….){
throw ex;
}自定義受檢異常和自定義非受檢異常
- 所有異常都必須是 Throwable 的子類。
- 如果您想編寫一個受檢異常,該異常會由“處理或宣告”規則自動強制執行,則需要擴充套件 Exception 類。
- 如果您想編寫一個執行時異常,則需要擴充套件 **RuntimeException** 類。
示例:自定義受檢異常
以下 Java 程式演示瞭如何建立自定義受檢異常。
import java.util.Scanner;
class NotProperNameException extends Exception {
NotProperNameException(String msg){
super(msg);
}
}
public class CustomCheckedException{
private String name;
private int age;
public static boolean containsAlphabet(String name) {
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (!(ch >= 'a' && ch <= 'z')) {
return false;
}
}
return true;
}
public CustomCheckedException(String name, int age){
if(!containsAlphabet(name)&&name!=null) {
String msg = "Improper name (Should contain only characters between a to z (all small))";
NotProperNameException exName = new NotProperNameException(msg);
throw exName;
}
this.name = name;
this.age = age;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter the name of the person: ");
String name = sc.next();
System.out.println("Enter the age of the person: ");
int age = sc.nextInt();
CustomCheckedException obj = new CustomCheckedException(name, age);
obj.display();
}
}編譯時異常
編譯時,上述程式會生成以下異常。
CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown throw exName; ^ 1 error
示例:自定義非受檢異常
如果您只是將自定義異常繼承的類更改為 RuntimeException,它將在執行時丟擲。
class NotProperNameException extends RuntimeException {
NotProperNameException(String msg){
super(msg);
}
}如果您執行前面的程式,用上述程式碼替換 NotProperNameException 類並執行它,它會生成以下執行時異常。
執行時異常
Enter the name of the person: Krishna1234 Enter the age of the person: 20 Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small)) at july_set3.CustomCheckedException.<init>(CustomCheckedException.java:25) at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP