Java 7 - Precise rethrow with a final Exception

前端 未结 3 799
礼貌的吻别
礼貌的吻别 2021-01-01 12:47

In previous versions of java, rethrowing an exception was treated as throwing the type of the catch parameter.

For example:

public static void test()         


        
3条回答
  •  轮回少年
    2021-01-01 12:57

    The reason why both compile is that an exception in a uni catch clause that is not subsequently modified is implicitly final (JLS 14.20).

    So for your example not to compile, you need to modify e in some way, for example:

    public static void test2() throws ParseException, IOException {
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        try {
            df.parse("x20110731");
            new FileReader("file.txt").read();
        } catch (Exception e) {
            if (e instanceof ParseException) {
                e = new ParseException("Better message", 0);
            } else {
                e = new IOException("Better message");
            }
            System.out.println("Caught exception: " + e.getMessage());
            throw e; //does not compile any more
        }
    }
    

提交回复
热议问题