0

Can somebody explain to me why the following code is OK for java compiler:

private InputStream getResourceAsStream(String resourceName) {
    return getClass().getClassLoader().getResourceAsStream(resourceName);
}

private byte[] readResourceToByteArray(String resourceName) {
    try (InputStream in = getResourceAsStream(resourceName)) {
        return IOUtils.toByteArray(in);
    } catch (IOException e) {
        throw new AssertionFailedError();
    }
}

But in the following one:

private InputStream getResourceAsStream(String resourceName) {
    return getClass().getClassLoader().getResourceAsStream(resourceName);
}

private byte[] readResourceToByteArray(String resourceName) {
    try (InputStream in = getResourceAsStream(resourceName)) {
        return IOUtils.toByteArray(in);
    } catch (IOException e) {
        throwException();
    }
}

private void throwException() {
    throw new AssertionFailedError();
}

I'm getting missing return statement java compilation error in method readResourceToByteArray() if it is clear that in catch block I'm throwing exception so no return should be needed ?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
martinsefcik
  • 346
  • 9
  • 20
  • Because the second snippet has a method call instead of directly throwing an exception. The compiler is able to understand that `throw new AssertionFailedError();` will result in an exception (hence the first snippet compiles fine), but it's not smart enough to know that `throwException()` will internally behave the same (so the second snippet won't compile). – BackSlash Mar 06 '19 at 15:58
  • What would happen if `throwException()` did not throw an exception? – Abhyudaya Sharma Mar 06 '19 at 15:58
  • The compiler doesn't inspect the contents of `throwException` when it parses the call, so it doesn't know that it throws an exception. – marstran Mar 06 '19 at 15:59
  • throwException() ..if you add a throws clause to this method, it will compile, else compiler has no way of knowing that an exception is being thrown by it – akshaya pandey Mar 06 '19 at 16:11
  • @akshayapandey "if you add a throws clause to this method, it will compile" ... no it won't. (at least not in Java 8, but I doubt that has been changed in later versions) – Tom Mar 06 '19 at 16:17

1 Answers1

2

In your first example, you are actually throwing an Exception which is known to the compiler at compile time, therefore no additional return statement is required.

In your second example, you are calling a method which may or may not throw an exception, compiler is not sure about this, therefore it is asking you for a return statement.

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111