java遗珠之多异常

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/lastsweetop/article/details/83058466

catch可以同时捕获多个异常,示例如下:

    public void writeList() {
        // The FileWriter constructor throws IOException, which must be caught.
        PrintWriter out = null;
        try {
            System.out.println("Entered try statement");
            out = new PrintWriter(new FileWriter("OutFile.txt"));
            for (int i = 0; i < SIZE; i++) {
                // The get(int) method throws IndexOutOfBoundsException, which must be caught.
                out.println("Value at: " + i + " = " + list.get(i));
            }
            out.close();
        } catch (IOException  | IndexOutOfBoundsException e) {
        	//ERROR e=new IOException("new io exception");
            e.printStackTrace();
        }

    }

但要注意的是如果是捕获多异常的话,异常变量默认就会变成final的了,不能再进行赋值。

单个异常不是final的

        catch (IOException  e) {
            e=new IOException("new io exception");
            e.printStackTrace();
        }

展开阅读全文

没有更多推荐了,返回首页