Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Groovy exception handling


May 14, 2021 Groovy


Table of contents


Any programming language requires exception handling to handle run-time errors so that the application's normal flow can be maintained.

Exceptions often break the normal flow of the application, which is why we need to use exception handling in our applications.

Exceptions fall broadly into the following categories -

  • Detect exceptions - Classes that extend the Throwable class (except RuntimeException and Error) are called Check exceptions egIOEx, SQLException, and so on. T he checked exception is checked at compile time.

A typical case is FileNotFoundEx. Suppose you have the following code in your application, which reads from the files in the E disk.

class Example {
   static void main(String[] args) {
      File file = new File("E://file.txt");
      FileReader fr = new FileReader(file);
   } 
}

If the file .txt is not on the E disk, the following exception is thrown.

Crawl: java.io.FileNotFoundException: E:'file.txt (the system could not find the specified file).

java.io.FileNotFoundException: E:\file.txt (the specified file could not be found).

  • Uncensored exceptions - Classes that extend RuntimeException are called uncensored exceptions, such as ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. E xceptions that are not checked are not checked during the compilation period, but are checked at runtime.

A typical scenario is ArrayIndexOutOfBoundsException, which occurs when you try to access an array index larger than the number of group leaders. The following is a typical example of this error.

class Example {
   static void main(String[] args) {
      def arr = new int[3];
      arr[5] = 5;
   } 
}

When the above code executes, the following exception is thrown.

Grab: java.lang.ArrayIndexOutOfBoundsException: 5

java.lang.ArrayIndexOutOfBoundsException:5

  • Error - The error could not be recovered. O utOfMemoryError, VirtualMachineError, AssertionError, etc.

These are errors that the program can never recover and will cause the program to crash.

The following illustration shows how to organize the exception hierarchy in Groovy. It is based on the hierarchy defined in Java.

Groovy exception handling

Catch an exception

Method captures exceptions using a combination of try and catch keywords. Try / catch blocks are placed around code that may generate exceptions.

try { 
   //Protected code 
} catch(ExceptionName e1) {
   //Catch block 
}

All code that might throw an exception is placed in a protected block of code.

In the catch block, you can write custom code to handle exceptions so that applications can recover from exceptions.

Let's look at a similar code example, where we see an array with an index value greater than the size of the array. But this time let's wrap our code in a try/catch block.

class Example {
   static void main(String[] args) {
      try {
         def arr = new int[3];
         arr[5] = 5;
      } catch(Exception ex) {
         println("Catching the exception");
      }
		
      println("Let's move on after the exception");
   }
}

When we run the program above, we will get the following results -

Catching the exception 
Let's move on after the exception

From the code above, we wrap the wrong code in the try block. In the catch block, we just catch our exception and output a message that an exception has already occurred.

Multiple capture blocks

You can have multiple catch blocks to handle multiple types of exceptions. For each catch block, depending on the type of exception thrown, you will write code to handle it accordingly.

Let's modify the code above to capture ArrayIndexOutOfBoundsException. The following is a snipper.

class Example {
   static void main(String[] args) {
      try {
         def arr = new int[3];
         arr[5] = 5;
      }catch(ArrayIndexOutOfBoundsException ex) {
         println("Catching the Array out of Bounds exception");
      }catch(Exception ex) {
         println("Catching the exception");
      }
		
      println("Let's move on after the exception");
   } 
}

When we run the program above, we will get the following results -

Catching the Aray out of Bounds exception 
Let's move on after the exception

From the above code, you can see that the ArrayIndexOutOfBoundsEx catch block was first caught because it means the standard of the exception.

finally block

The final block follows the try block or catch block. The finally block of code is always executed regardless of the exception.

Use the find block to run any cleanup type statement you want to execute, regardless of what happens in the protected code. The syntax of the block is as follows.

try { 
   //Protected code 
} catch(ExceptionType1 e1) { 
   //Catch block 
} catch(ExceptionType2 e2) { 
   //Catch block 
} catch(ExceptionType3 e3) { 
   //Catch block 
} finally {
   //The finally block always executes. 
}

Let's modify the code above us and add the findy block. The following is a snipper.

class Example {
   static void main(String[] args) {
      try {
         def arr = new int[3];
         arr[5] = 5;
      } catch(ArrayIndexOutOfBoundsException ex) {
         println("Catching the Array out of Bounds exception");
      }catch(Exception ex) {
         println("Catching the exception");
      } finally {
         println("The final block");
      }
		
      println("Let's move on after the exception");
   } 
} 

When we run the program above, we will get the following results -

Catching the Array out of Bounds exception 
The final block 
Let's move on after the exception

Here's the exception method provided in Groovy -

public String getMessage()

Returns a detailed message that an exception has occurred. This message is initialized in the Throwable constructor.

public Throwable getCause()

Returns the reason for the exception represented by the Throwable object.

public String toString()

Returns the name of the class that is connected to the result of getMessage().

public void printStackTrace()

Print the results of toString() with the stack trace to System.err, the error output stream.

public StackTraceElement [] getStackTrace()

Returns an array that contains each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.

public Throwable fillInStackTrace()

Use the current stack trace to populate the stack trace of this Thisrowable object and add any previous information to the stack trace.

Example

Here's an example of code that uses some of the methods given above -

class Example {
   static void main(String[] args) {
      try {
         def arr = new int[3];
         arr[5] = 5;
      }catch(ArrayIndexOutOfBoundsException ex) {
         println(ex.toString());
         println(ex.getMessage());
         println(ex.getStackTrace());  
      } catch(Exception ex) {
         println("Catching the exception");
      }finally {
         println("The final block");
      }
		
      println("Let's move on after the exception");
   } 
}

When we run the program above, we will get the following results -

java.lang.ArrayIndexOutOfBoundsException: 5 
5 
[org.codehaus.groovy.runtime.dgmimpl.arrays.IntegerArrayPutAtMetaMethod$MyPojoMetaMet 
hodSite.call(IntegerArrayPutAtMetaMethod.java:75), 
org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) ,
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) ,
org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) ,
Example.main(Sample:8), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,
java.lang.reflect.Method.invoke(Method.java:606),
org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93),
groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325),
groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1443),
org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:893),
groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:287),
groovy.lang.GroovyShell.run(GroovyShell.java:524),
groovy.lang.GroovyShell.run(GroovyShell.java:513),
groovy.ui.GroovyMain.processOnce(GroovyMain.java:652),
groovy.ui.GroovyMain.run(GroovyMain.java:384),
groovy.ui.GroovyMain.process(GroovyMain.java:370),
groovy.ui.GroovyMain.processArgs(GroovyMain.java:129),
groovy.ui.GroovyMain.main(GroovyMain.java:109),
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,
java.lang.reflect.Method.invoke(Method.java:606),
org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109),
org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131),
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,
java.lang.reflect.Method.invoke(Method.java:606),
com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)]
 
The final block 
Let's move on after the exception