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

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

问题描述

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

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 并让它extend Exception.

All you need to do is create a new class and have it extend Exception.

如果你想要一个未选中的Exception,你需要extend RuntimeException.

If you want an Exception that is unchecked, you need to extend RuntimeException.

注意:经过检查的Exception 要求您在try/中将Exception 括起来catch 块或在方法声明上有一个throws"子句.(如 IOException)未检查的 Exceptions 可能会像已检查的 Exceptions 一样被抛出,但您不需要以任何方式显式处理它们(<代码>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天全站免登陆