![](/img/trans.png)
[英]Arrays.sort throws compile-time error 'Anonymous class derived from Comparator..'
[英]Custom exception class throws compile-time error
我正在嘗試創建自己的異常,它擴展了異常 class,但是當我嘗試拋出它時,編譯器會拋出編譯時錯誤。
這是我的例外 class:
package Exception;
public class notAdultException extends Exception {
@Override
public String toString() {
return ("you are not adult");
}
}
這是我嘗試拋出異常的地方:
int Age = 16;
try {
if (Age < 18) {
throw new notAdultException();
}
catch (notAdultException t) {
System.out.println(t);
}
這是錯誤消息:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
No exception of type notAdultException can be thrown; an exception type must be a sublass of Throwable
No exception of type notAdultException can be thrown; an exception type must be a sublass of Throwable
at Exception.Exception.main(Exception.java:44)
問題是您在同一個 package 中有一個名為Exception
的 class,因此您需要有資格訪問java.lang.Exception
。 演示
public class notAdultException extends java.lang.Exception {
@Override
public String toString(){
return "you are not adult";
}
}
作為旁注,您應該始終遵循Java 命名約定,例如,您的 class 的名稱應該是NotAdultException
而不是notAdultException
並且您的my.exceptions
的名稱應該是類似的東西。
嘗試這個:
public class notAdultException extends Exception {
public notAdultException(String message) {
super(message);
}
}
不要忘記導入 java.lang.Exception (或使用上面提到的完整限定符。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.