自定义异常类抛出编译时错误

时间:2020-08-06 23:45:18

标签: java exception

我正在尝试创建自己的异常,该异常扩展了Exception类,但是当我尝试抛出该异常时,编译器将引发编译时错误。

这是我的异常类:

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)

2 个答案:

答案 0 :(得分:0)

问题是您在同一软件包中有一个名为Exception的类,因此您需要限定对java.lang.Exception的访问。 Demo

public class notAdultException extends java.lang.Exception {
    @Override
    public String toString(){
        return "you are not adult";
    }
}

答案 1 :(得分:0)

尝试一下:

getCard() {
    this.socket.emit("getCard");
    let answer = "";
    this.socket.on("card", key => {
      console.log("key received");
      console.log(key);
      answer = key;
    });
    return answer;
 }

别忘了导入java.lang.Exception(或使用上述的完整限定符。)

相关问题