I try to learn something new every day when it comes to Groovy, or at the very least to challenging my understanding of some of the tenets of the syntax that I think I already know.

This morning I was playing around with the assert statement in ScriptRunner, trying to understand the nuances of it.   I was getting frustrated because I wanted the assertion to fail, but then for the script to keep going.  I couldn’t figure out how to capture the error without having the script stop.

I tried a few things.   I know you can include a log statement to the end of an assertion, like so:

assert (1 == 2) : "Assertion failed" 

 

java.lang.AssertionError: Assertion failed. Expression: (1 == 2)
	at org.codehaus.groovy.runtime.InvokerHelper.assertFailed(InvokerHelper.java:438)
	at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.assertFailed(ScriptBytecodeAdapter.java:670)
	at Script205.run(Script205.groovy:2)

But even with the inclusion of the log statement, my script would grind to a halt when the assertion failed.    I also tried putting the assertion in a try/catch statement, but that didn’t work at all.

I then realized that I had no idea what the functional difference between an assertion and a try/catch statement actually was.  Moreover, I didn’t know when it was appropriate to use one or the other.

From what I read, it seems that assertions are generally for testing code, and aren’t appropriate in production.  Try/catch statements are for catching exceptions or edge cases.  They two are not actually equivalent or interchangeable.

If you want to make assertions in production code, Groovy allows you to make assertions without using the assert statement. For example, the below code evaluates a statement, but instead of bringing the script to a halt it returns the result of the comparison:

def test = 1 == 2

return "Test result: ${test.booleanValue()}"

This would allow the code to keep running, and to react to the failure of the assertion accordingly.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>