Mauro Ciancio
Mauro Ciancio

Reputation: 436

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

Upvotes: 4

Views: 839

Answers (2)

Chris Joslin
Chris Joslin

Reputation: 63

In the second case you are not catching the exception thrown; so that behavior is expected. In the first case, 'Exception' is the variable assigned to the exception thrown. Print that out and you'll see it's "java.lang.RuntimeException".

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500835

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.

Upvotes: 11

Related Questions