共計 886 個字符,預計需要花費 3 分鐘才能閱讀完成。
要定義自定義的編譯時異常,需要創建一個繼承自 java.lang.Exception
類的子類,并重寫 toString()
方法來提供異常信息。
以下是一個自定義編譯時異常的示例:
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
語句拋出自定義異常。例如:
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
塊來捕獲和處理這個異常。
可以根據自己的需要在自定義異常類中添加其他屬性和方法,例如,可以添加 getErrorCode()
和getErrorMessage()
來獲取異常的錯誤代碼和錯誤信息。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2023-12-09