您可以在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的子類別。
如果您想要寫一個由Handle或Declare規則自動強制執行的已檢查異常,您需要擴充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中的自訂異常的詳細內容。更多資訊請關注PHP中文網其他相關文章!