如何编写自定义异常? [英] How can I write custom Exceptions?
问题描述
如何创建新的异常
与预制类型不同?
How can I create a new Exception
different from the pre-made types?
public class InvalidBankFeeAmountException extends Exception{
public InvalidBankFeeAmountException(String message){
super(message);
}
}
它将显示 InvalidBankFeeAmountException的警告
It will show the warning for the InvalidBankFeeAmountException which is written in the first line.
推荐答案
所有你需要做的是创建一个新的 class
,并且它有扩展异常
。
All you need to do is create a new class
and have it extend Exception
.
如果你想要一个异常
未被选中,您需要扩展RuntimeException
。
If you want an Exception
that is unchecked, you need to extend RuntimeException
.
注意:一个选中的异常
是一个需要您围绕 Exception
try
/ catch
block或者有一个'$ code> throws '在方法声明中。 (如 IOException
)未选中异常
可能会像检查异常
,但是您不需要以任何方式显式处理它们( IndexOutOfBoundsException
)。
Note: A checked Exception
is one that requires you to either surround the Exception
in a try
/catch
block or have a 'throws
' clause on the method declaration. (like IOException
) Unchecked Exceptions
may be thrown just like checked Exceptions
, but you aren't required to explicitly handle them in any way (IndexOutOfBoundsException
).
例如:
public class MyNewException extends RuntimeException {
public MyNewException(){
super();
}
public MyNewException(String message){
super(message);
}
}
这篇关于如何编写自定义异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!