如何在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);
    }
}