如何在Java中定义自定义异常类,最简单的方法是什么? [英] How to define custom exception class in Java, the easiest way?
本文介绍了如何在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中定义自定义异常类,最简单的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文