如何在Java中定义自定义异常类,最简单的方法?

如何在Java中定义自定义异常类,最简单的方法?

问题描述:

我正在尝试以最简单的方式定义我自己的异常类,这就是我得到的:

I'm trying to define my own exception class the easiest way, and this is what I'm getting:

public class MyException extends Exception {}

public class Foo {
  public bar() throws MyException {
    throw new MyException("try again please");
  }
}

Java 编译器是这样说的:

This is what Java compiler says:

cannot find symbol: constructor MyException(java.lang.String)

我有一种感觉,这个构造函数必须继承自 java.lang.Exception 不是吗?

I had a feeling that this constructor has to be inherited from java.lang.Exception, isn't it?

不,您不会继承"非默认构造函数,您需要在类中定义采用 String 的构造函数.通常,您在构造函数中使用 super(message) 来调用父构造函数.例如,像这样:

No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message) in your constructor to invoke your parent constructor. For example, like this:

public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}