Friday, September 4, 2015

Java Exception Fun

Look at this:
public class Test {

  public void f() {

  public void g() {
    try {
    } catch (Exception e) {
      throw e;
Does this compile? Notice that method g() is throwing an exception object declared to be of type Exception but does not actually mention this in its throws clause. In Java 6 this indeed does not compile: unreported exception java.lang.Exception; must be caught or declared to be thrown
      throw e;
1 error
But it came as somewhat of a surprise to me that this compiles just fine in both Java 7 and Java 8! Thinking back this was of course part of the exception improvements made in Java 7. Goes to show that you can still come across little fun nuggets like this after all these years :-).

No comments:

Post a Comment