public class MyException extends Exception{}与public class MyException extends RuntimeException{}的区别?

解决方案 »

  1.   

    RuntimeException 的子类不用显式的抛出,就像空指针异常一样 public class MyException extends Exception{} 这样写就要 catch 或throws 了
      

  2.   

    RuntimeException属于编程错误, 将被自动捕获, 不用自己写try, catch. 当然想捕获也可以, 但是没有这个必要, 如果是大程序也不可能做到.
    看Thinking in java中的一段:
    a RuntimeException represents a programming error:An error you cannot anticipate. For example, a null reference that is outside of your control.
    An error that you, as a programmer, should have checked for in your code (such as ArrayIndexOutOfBoundsException where you should have paid attention to the size of the array).大致是说可能是个无法预期的错误, 比如你控制范围外传来一个空的引用. 还有就是作为程序员应该检查出来的错误, 比如数组下标越界, 这个是编程错误, 应该修改代码, 而不是依靠异常处理.
      

  3.   

    RuntimeException 可以不用catch
      

  4.   

    我的意思是为什么要这样自定义异常?而不是问什么是RuntimeException?public class MyException extends RuntimeException{}
      

  5.   

    为什么?
    这个当然要靠你自己分析和理解, 你觉得有必要用就用. 比如在某种情况下出现的错误你觉得是个编程错误, 就throw一个RuntimeException或其子类.
      

  6.   

    Albert_1030() ( ) 信誉:100 
    20--都不够分的
    -----------------------------
    分多的是,可以另外开贴给分。