I have following code:
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 }
...
}
The interesting part of this code is, it's allowing parent class to be caught by a child, I am not sure why this is the case, though I also added following few more lines of code to understand it:
Try 1 (no compile-time error):
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 }
...
}
Try 2 (compile time error at line 8
but line 6
worked):
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();
...
}
Also, I know downcasting is allowed when the type is same at runtime, but then try 1 line 5 worked (maybe at runtime it will fail if ArrayIndexOutOfBoundsException occurs)?
Downcasting is allowed when there is a possibility that it suceeds at run time:
Object o = getSomeObject();
String s = (String) o; // this is allowed because o could reference a String