为什么要在Java中编写自定义异常类 [英] Why should we write custom exception classes in Java

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

问题描述

编写自定义异常类的目的主要是什么是相同的。
例如, NullPointerException

  class NullPointerException extends RuntimeException {
private static final long serialVersionUID = 5162710183389028792L;


public NullPointerException(){
super();
}


public NullPointerException(String s){
super(s);
}
}

这是大多数异常类的基本模板已经看到并创造了。



我可以想到的一个目的是处理这些异常。但是不能这样基于异常消息?大多数情况下,我们为每个异常类型编写单个处理代码我知道有这样的'例外'。



但还有什么吗?不,这重复你自己,只有类名更改?



还有没有任何JDK异常类有一些代码比这个?

解决方案

我可以想到几个原因:




  • 有多个异常类允许程序员在他们的 catch 子句中特定,只能捕获他们关心的异常,并且知道该怎么做。

  • 一个异常类可以携带引起异常的错误信息。例如, ArrayIndexOutOfBoundsException 携带违规数组索引,SQL异常往往会携带数据库特定的错误代码和消息。

  • 异常规范 - 列表异常 - 可用于在编译时检查正确性。


What is the purpose of writing custom exception classes when mostly what it does is same. For eg, NullPointerException:

class NullPointerException extends RuntimeException {
      private static final long serialVersionUID = 5162710183389028792L;


      public NullPointerException() {
          super();
      }


      public NullPointerException(String s) {
          super(s);
      }
}

This is the basic template for most exception classes that I have seen and created.

One purpose I can think of is in handling these exception.But then cant this be based on Exception Message?. Mostly we write single handling code for each exception type. I know there are 'exceptions' to this.

But is there anything more to it? Isnt this repeating yourself where only the class name changes?

Also are there any JDK Exception classes that has some code than this?

解决方案

I can think of several reasons:

  • Having multiple exception classes allows the programmer to be specific in their catch clauses, and only catch the exceptions they care about and know what to do with.
  • An exception class can carry information about the error that's caused the exception. For example, ArrayIndexOutOfBoundsException carries the offending array index, and SQL exceptions tends to carry database-specific error codes and messages.
  • Exception specifications -- that list exception classes -- can be used to check correctness at compile time.

这篇关于为什么要在Java中编写自定义异常类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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