Java平台有那么多异常了,为什么我们还需要自定义异常。看了一段英文资料,还是没弄明白。贴出来大家共同讨论。1.Do you need an exception type that isn't represented by those in the Java platform? 
2.Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors? 
3.Does your code throw more than one related exception? 
4.If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained? 

解决方案 »

  1.   

    举个例子吧 假如说有个业务需求 返回1就应该报异常 但是JAVA 里面自带的不会有这种异常 ,这时候就需要自己定异常了!
      

  2.   

    If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?  
      

  3.   

    java里是有很多的异常处理,不一定都是符合实际项目的,实际中要根据项目的需求在自定义异常的。
      

  4.   

    自定义异常是为了设置异常链的起点。一般情况下,我们都是允许每个程序员看到所有的异常信息,这个时候大多数都是把下一层的异常直接重掷到上一层。然而在多层次的结构中,我们有时候需要隐藏底层异常(这种异常的信息很多,很枯燥) ,而给消费者提供一个更为直观的异常,这个时候我们需要自定义异常。有的异常类jdk已经给我们提供,比如常用的IllegalArgumentException。如果你想在此再作包装,你可以创建自己的异常类。如此,消费者将以此异常作为异常链的起点。
      

  5.   

    1.Do you need an exception type that isn't represented by those in the Java platform? 
    answer: yes,do need. sometimes the personal business does require it just like the upper one said.2.Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors? 
    answer: yes, it helps. i think if they could differentiate them, it could help them to better understand the situation when the exception occurs.3.Does your code throw more than one related exception? 
    answer: yes, it does. including those exceptions from the java platform, some of them are related with each other.i think it maybe could inhance the systematic property of the exceptions.it just proves they are integrated into one platform.4.If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?  
    answer: maybe they have not. my package should be independent and self-contained. why? maybe loose coupling makes it.就像楼上说的具体业务的要求,系统异常不可能面面俱到,自定义就是为了在实际中填补应用空白,另外的,自己的一套关联度强的异常可控性高,识别度高,和平台异常搭配使用,满足业务需求和系统需求。
      

  6.   

    创建自定义异常是为了表示应用程序的一些错误类型,为代码可能发生的一个或多个问题提供新含义。可以显示代码多个位置之间的错误的相似性,也可区分代码运行时可能出现的相似问题的一个或多个错误,或给出应用程序中一组错误的特定含义。
    http://book.csdn.net/bookfiles/150/1001506505.shtml
    楼主看看这个吧。