本文介绍了如何在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);
}
}
这篇关于如何在Java中定义自定义异常类,最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!