Groovy Exception handling

Exception handling

Groovy lets the programmer decide to catch the exception or not. In the following example, the developer tries to open and read the contents of a file. He does not need to surround the method with a try and catch block, when he knows that the file exists. Groovy gives the programmer control over the exceptions, so he chooses to throw one but he does not need to. Java would not compile the code because it expects a try and catch block that throws the exception FileNotFoundException

//Checked and Unchecked exceptions
def reader=new FileReader("test.txt")
println "Key is : "+reader.getText()
readerIn=new FileReader("testNo.txt")
println "key is: " +readerIn.getText()
catch(FileNotFoundException e){
println "Could not find the file"

The example above shows two ways of opening a fle: With and without a try and catch block. When the developers know that a file exists – As shown in the first example above – he doesn’t need to surround it with a try and catch. Like stated earlier, the developer can choose whether he wants to catch the exception or not – This happens in the second example above. Sometimes, code needs to catch more than one exception. Groovy allows the developer to catch all

exceptions in one catch, instead of writing a catch statement for each try

URL newUrl=new URL("");
InputStream str=newUrl.openStream();
printls "Error: "+ex

Note that the code above only throws one exception: The function openFile does not exist so it directly throws an exception. If it existed, another exception would be thrown since the URL is formatted wrong. The catch would show the exception: This is the same catch as the one from open File


Testing in Groovy is, like testing in Java, very extensive. A common way to test a application is with JUnit testing. The name for JUnit in Groovy is GUnit. Codehaus and IBM have written articles about unit testing in Groovy. Documentation on their findings can be found on the following websites:

Because the subject GUnit doesn’t support our main question, this will not be fully described. Basically, it is the same as JUnit testing.

Database Integration

Groovy provides the user with a wrapper around the standard Java classes, adding more functionality and ease of use when working with databases. It is important to understand that Groovy currently doesn’t replace all of Java’s original databases connectivity, as the JDBC is still in use.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s