英文:
Custom exception class throws compile-time error
问题
我正在尝试创建自己的异常,该异常扩展了Exception类,但当我尝试抛出它时,编译器会抛出编译时错误。
这是我的异常类:
package Exception;
public class notAdultException extends Exception {
@Override
public String toString() {
return "你不是成年人";
}
}
这是我尝试抛出异常的地方:
int Age = 16;
try {
if (Age < 18) {
throw new notAdultException();
}
} catch (notAdultException t) {
System.out.println(t);
}
这是错误消息:
Exception in thread "main" java.lang.Error: 无法解析的编译问题:
不能抛出类型为notAdultException的异常;异常类型必须是Throwable的子类
不能抛出类型为notAdultException的异常;异常类型必须是Throwable的子类
at Exception.Exception.main(Exception.java:44)
英文:
I am trying to create my own exception, which extends the Exception class, but when I try to throw it, the compiler throws a compile-time error.
Here is my exception class:
package Exception;
public class notAdultException extends Exception {
@Override
public String toString() {
return ("you are not adult");
}
}
Here is where I try to throw the exception:
int Age = 16;
try {
if (Age < 18) {
throw new notAdultException();
}
catch (notAdultException t) {
System.out.println(t);
}
And here is the error message:
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)
答案1
得分: 1
The issue is that you have a class named Exception
in the same package, so you will need to qualify access to java.lang.Exception
.
public class notAdultException extends java.lang.Exception {
@Override
public String toString(){
return "you are not adult";
}
}
As a side note, you should always follow the Java naming conventions e.g. the name of your class should be NotAdultException
instead of notAdultException
and the name of your package should be something like my.exceptions
.
英文:
The issue is that you have a class named Exception
in the same package, so you will need to qualify access to java.lang.Exception
. <sup>Demo</sup>
public class notAdultException extends java.lang.Exception {
@Override
public String toString(){
return "you are not adult";
}
}
As a side note, you should always follow the Java naming conventions e.g. the name of your class should be NotAdultException
instead of notAdultException
and the name of your package should be something like my.exceptions
.
答案2
得分: 1
public class notAdultException extends Exception {
public notAdultException(String message) {
super(message);
}
}
不要忘记导入 java.lang.Exception(或者如上面提到的使用完整的限定符)。
英文:
Try this:
public class notAdultException extends Exception {
public notAdultException(String message) {
super(message);
}
}
Don't forget to import java.lang.Exception (or use the full qualifier as mentioned above.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论