要定義自定義的編譯時(shí)異常,需要?jiǎng)?chuàng)建一個(gè)繼承自java.lang.Exception
類(lèi)的子類(lèi),并重寫(xiě)toString()
方法來(lái)提供異常信息。
以下是一個(gè)自定義編譯時(shí)異常的示例:
public class MyCustomException extends Exception {
private int errorCode;
private String errorMessage;
public MyCustomException(int errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
@Override
public String toString() {
return "MyCustomException{" +
"errorCode=" + errorCode +
", errorMessage='" + errorMessage + '\'' +
'}';
}
}
然后,你可以在代碼中使用throw
語(yǔ)句拋出自定義異常。例如:
public class Test {
public static void main(String[] args) {
try {
process();
} catch (MyCustomException e) {
System.out.println(e.toString());
}
}
public static void process() throws MyCustomException {
// 模擬拋出自定義異常
throw new MyCustomException(500, "自定義異常信息");
}
}
在上面的例子中,process()
方法模擬拋出了自定義異常MyCustomException
,并且在main()
方法中使用try-catch
塊來(lái)捕獲和處理這個(gè)異常。
可以根據(jù)自己的需要在自定義異常類(lèi)中添加其他屬性和方法,例如,可以添加getErrorCode()
和getErrorMessage()
來(lái)獲取異常的錯(cuò)誤代碼和錯(cuò)誤信息。