Java_exception

RuntimeException#

  • You never need to write an exception specification saying that a method might throw a RuntimeException,
    because they are unchecked exceptions. it's dealt with automatically.

  • Keep in mind that only exceptions of type RuntimeException can be ignored in your coding

  • finally return之前仍然会执行


Pitfall#

  • It's possible for an exception to simply be lost.

This happens with a particular configuration using a finally clause

    public static void main(String[] args) {
    try {
        LostMessage lm = new LostMessage();
        try {
        lm.f();
        } finally {
        lm.dispose();  //throw another exception will be         
                          replace the former exception
        }
        } catch(Exception e) {
        System.out.println(e);
        }
    }
    
  • An even simpler way to lose an exception is just to return from inside a finally clause:
    public static void main(String[] args) {
    try {
            throw new RuntimeException();
        } finally {
        // Using ‘return’ inside the finally block
        // will silence any thrown exception.
        return;
        }
    }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容