![](/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.