如何编写自定义异常? [英] How can I write custom Exceptions?

查看:192
本文介绍了如何编写自定义异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建新的异常与预制类型不同?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆