7 November 2013

How to catch assert exception in Groovy?

I never used assert in Java,but I found assert can be useful is Groovy,but ... here is story:
Solution for Groovy 2.x (I guess ,it works on all version of Groovy.I just didn't test it.

STORY:

I started from catch assert with Exception,but ...as usual ... it was a bad ideas as,when I run this code:

try{
assert 3>4
}catch(Exception e){
println(e.getMessage())
}

then ,I was welcome with error:

Exception thrown
Nov 07, 2013 10:04:05 AM org.codehaus.groovy.runtime.StackTraceUtils sanitize

WARNING: Sanitizing stacktrace:

Assertion failed:

assert 3>4
        |
        false

SOLUTION:
Quick look to Groovy docs and I found that I should use AssertionError instead:

try{
assert 3>4
}catch(
AssertionError  e){
println(e.getMessage())
}


CONCLUSION:
Due dynamic nature of Groovy it is good to check Exceptions chapter on Groovy:
http://groovy.codehaus.org/JN3035-Exceptions

as they handle things differently.
(Groovy 2.x has amazing multi catch option!

No comments:

Post a Comment