Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy catch statement weird behavior

I have the following 2 groovy snippets that should do the same but they don't.

try {
  throw new RuntimeException()
} catch (IllegalStateException) {
  println("hello!")
}

The output from this 'hello!'

try {
  throw new RuntimeException()
} catch (IllegalStateException e) {
  println("hello!")
}

And the output from this one is an unexpected exception:

Caught: java.lang.RuntimeException
java.lang.RuntimeException
    at 2.run(2.groovy:2)

Please note the only difference is that in one snippet there is no e parameter in the catch block.

I'm running the following version of groovy and JVM.

groovy --version Groovy Version: 2.0.5 JVM: 1.6.0_37 Vendor: Sun Microsystems Inc. OS: Linux

Is this an expected behavior or is it a bug in the compiler? Thanks

like image 469
Mauro Ciancio Avatar asked Dec 20 '22 13:12

Mauro Ciancio


1 Answers

In the first case, you're introducing a variable called IllegalStateException. It's equivalent to:

try {
  throw new RuntimeException()
} catch (Exception IllegalStateException) {
  println("hello!")
}

In the second case, you're only catching IllegalStateException, which isn't the type of the exception being thrown, hence the catch block doesn't catch it.

It's not equivalent to the C# meaning, where you'd be saying that you only want to catch IllegalStateException, but you don't need a variable for it as you don't care about the exception object.

See the "Catch any exception" part of the Groovy style and language feature guidelines for Java developers documentation.

like image 102
Jon Skeet Avatar answered Dec 26 '22 19:12

Jon Skeet