Java 中的 Exception 例項是已檢查異常還是未檢查異常?
異常是在程式執行期間發生的錯誤(執行時錯誤)。當發生異常時,程式會突然終止,異常行之後的程式碼將不會執行。
Java中有兩種型別的異常。
- 未檢查異常 - 未檢查異常是在執行時發生的異常。這些也稱為執行時異常。這些包括程式設計錯誤,例如邏輯錯誤或API的不正確使用。執行時異常在編譯時會被忽略。
- 已檢查異常 - 已檢查異常是在編譯時發生的異常,這些也稱為編譯時異常。這些異常在編譯時不能被簡單地忽略;程式設計師應該處理這些異常。
異常層次結構
在Java中,所有異常都是java.lang.Throwable類的子類。
Throwable和Exception類的所有例項都是已檢查異常,RuntimeException類的例項是執行時異常。
例如,如果您透過擴充套件Exception類來建立一個使用者定義的異常,則會在編譯時丟擲此異常。
示例
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
廣告