3

In Chapter 3 of the Oracle OCP Java SE 8 Programmer II Study Guide, it says the following (pg. 184):

In Java 6, we can't write catch (Exception e) and merely throw specific exceptions. If we tried, the compiler would still complain:

unhandled exception type Exception.

What does this mean? What is a specific example?

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • 1
    did u try? `... catch(Exception e) {throw e;}` – Eugene Nov 25 '18 at 21:44
  • What is the example to try? It says throw specific exceptions. –  Nov 25 '18 at 21:45
  • aren't you missing `throws Exception` next to the method declaration? – m.antkowicz Nov 25 '18 at 21:46
  • `try { throw new Exception(); } catch (Exception e) { throw e; }` specific example - try adding this code to a method. – Eugene Nov 25 '18 at 21:48
  • The change is also explained in this related question https://stackoverflow.com/questions/40186276/rethrowing-exception-without-requiring-throws-exception (and several others), but in the opposite direction - with assuming knowledge of the previous behavior. – Hulk Nov 26 '18 at 08:06

1 Answers1

6

Consider the following example:

Integer add (Integer a, Integer b) {
    try {
        return a + b;
    } catch (Exception e) {
        throw e;
    }
}

Of course, the addition of two numbers cannot throw any checked exceptions. However, in Java 6, the compiler sees throw e, where e is an Exception, and concludes that the method can throw any Exception. This requires add to declare that it throws Exception.

From Java 7, the compiler is a bit more clever with working out what types of exception e can be when it is re-thrown. In this case, it is able to work out that e can only be a RuntimeException (which is unchecked), and thus the declaration that add throws Exception is no longer necessary.

Joe C
  • 15,324
  • 8
  • 38
  • 50