使用子异常类来捕获父类。怎么可能?

时间:2018-02-23 16:56:56

标签: java exception-handling java-7

我有以下代码:

1 public static byte[] foo() throws IOException {

    ...

2   try (DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream())) {
3        wr.write(stringObj.getBytes("UTF-8"));
4        wr.flush();
5    } catch (Exception e) {
6        throw e;
7    }

    ...

}

这段代码的有趣部分是,它允许父类被子进程捕获,我不知道为什么会这样,尽管我还添加了几行代码来理解它:

尝试1(无编译时错误):

1 public static byte[] foo() throws IOException {

    ...

2   try (DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream())) {
3        wr.write(stringObj.getBytes("UTF-8"));
4        wr.flush();

5         throw new ArrayIndexOutOfBoundsException();

6    } catch (Exception e) {
7        throw e;
8    }

    ...

}

尝试2(编译时错误line 8line 6有效):

1 public static byte[] foo() throws IOException {

    ...

2   try (DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream())) {
3        wr.write(stringObj.getBytes("UTF-8"));
4        wr.flush();
5    } catch (Exception e) {
6        throw e;
7    }

8    throw new Exception();
    ...

}

另外,我知道downcasting is allowed在运行时类型是相同的,但是然后尝试1行5工作(可能在运行时它会失败,如果发生ArrayIndexOutOfBoundsException)?

  

如果有可能在运行时间成功,则允许向下转换:

     

Object o = getSomeObject();

     

String s = (String) o; // this is allowed because o could reference a String

0 个答案:

没有答案