简体   繁体   English

自定义异常 class 引发编译时错误

[英]Custom exception class throws compile-time error

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.我正在尝试创建自己的异常,它扩展了异常 class,但是当我尝试抛出它时,编译器会抛出编译时错误。

Here is my exception class:这是我的例外 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)

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 .问题是您在同一个 package 中有一个名为Exception的 class,因此您需要有资格访问java.lang.Exception Demo演示

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 eg the name of your class should be NotAdultException instead of notAdultException and the name of your package should be something like my.exceptions .作为旁注,您应该始终遵循Java 命名约定,例如,您的 class 的名称应该是NotAdultException而不是notAdultException并且您的my.exceptions的名称应该是类似的东西。

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.)不要忘记导入 java.lang.Exception (或使用上面提到的完整限定符。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM