Copyright HébergementWebs.com - License GPL

Groovy - Exception handling

Groovy tutorial   2020-11-21 01:49:56

Groovy - Exception Handling Exception handling is required in any programming language to handle runtime errors so that the normal flow of the application can be maintained. The exception normally disrupts the normal flow of the application, which is why we need to use exception handling in our application. Exceptions are broadly classified into the following categories - Exception checked - Classes that extend Throwable class except RuntimeException and Error are called checked exceptions egIOException, SQLException etc. Checked exceptions are checked at compile time. A classic case is the FileNotFoundException. Suppose you have the following code in your application that reads a file in drive E. class Example {static void main (String args) {File file = new File ( "E: //fichier.txt "); FileReader en = new FileReader (file); }} if the file (file.txt) is not present in drive E, the following exception will be raised. Caught: java.io.FileNotFoundException: E: file.txt (The system cannot find the specified file). java.io.FileNotFoundException: E: file.txt (The system cannot find the specified file). Unchecked exception - Classes that extend RuntimeException are called unchecked exceptions, for example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException , etc. Unchecked exceptions are not checked at compile time, rather they are checked at run time. A classic case is the ArrayIndexOutOfBoundsException which occurs when you try to access an index of an array that is greater than the length of the tableau. Here is a typical example of this kind of error. class Example {static void main (String args) {def arr = new int [3]; arr [5] = 5; }} When the above code is executed, the following exception will be raised. Caught: java.lang.ArrayIndexOutOfBoundsException: 5 java.lang.ArrayIndexOutOfBoundsException: 5 Error - The error is unrecoverable eg OutOfMemoryError, VirtualMachineError, AssertionError etc. These are errors that the program can never recover from and will cause the program to crash. The following diagram shows how the exception hierarchy in Groovy is organized. Everything is based on the hierarchy defined in Java. Catch exceptions A method catches an exception using a combination of the words - try and catch keys. A try / catch block is placed around code that might throw an exception. try {// Protected code} catch (ExceptionName e1) {// Catch block} All your code that could raise an exception is placed in the protected code block. In the catch block, you can write custom code to handle your exception so that the application can recover from the exception. Let"s look at an example of the similar code we saw above to access an array with an index value that is greater than the size of the array. But this time, let"s wrap our code in a try / catch block. Live demo class Example {static void main (String args) {try {def arr = new int [3] ; arr [5] = 5; } catch (Exception ex) {println ( "Catch exception ");} println ( "Let"s move on after the exception "); }} When we run the above program, we will get the following result - Catch the exception Let"s go to the exception after the exception From the code above, we wrap the bad code in the try block. In the catch block, we just catch our exception and send a message indicating that an exception has occurred. Several Catch blocks We can have several catch blocks to handle several types of exceptions. For each catch block, depending on the type of exception raised, you would write code to handle it accordingly. Let"s modify our code above to specifically catch the ArrayIndexOutOfBoundsException exception. Here is the code snippet. Live demo class Example {static void main (String args) {try {def arr = new int [3]; arr [5] = 5; } catch (ArrayIndexOutOfBoundsException ex) {println ( "Array catch exception out of range "); } catch (Exception ex) {println ( "Catch exception "); } println ( "Let"s move on after the exception "); }} When we run the above program we will get the following result - Catch the Aray out of range exception Let " s move on after the exception From the code above, you can see that the ArrayIndexOutOfBoundsException catch block is caught first because it signifies the criteria for the exception. Final Block The finally block follows a try block or a catch block. A finally code block always executes, regardless of the occurrence of an exception. Using a finally block allows you to execute all instCleanup type ructions you want to perform, no matter what happens in the protected code. The syntax of this block is given below. try {// Protected code} catch (ExceptionType1 e1) {// Catch block} catch (ExceptionType2 e2) {// Catch block} catch (ExceptionType3 e3) { // Catch block} finally {// The fina lly block always executes. } Let"s modify our code above and add the last block of code. Here is the code snippet. class Example {static void main (String args) {try {def arr = new int [3]; arr [5] = 5; } catch (ArrayIndexOutOfBoundsException ex) {println ( "Array catch exception out of range "); } catch (Exception ex) {println ( "Catch exception "); } finally {println ( "The final block "); } println ( "Let"s move on after the exception "); }} When we run the above program, we will get the following result - Array exception out of range The final block Let follow the exception Here are the exception methods available in Groovy - public String getMessage () Returns a detailed message about the exception that occurred. This message is initialized in the Throwable constructor. public Throwable getCause () Returns the cause of the exception represented by a Throwable object. public String toString () Returns the name of the class concatenated with the result of getMessage () public void printStackTrace () Prints the result of toString () with stack trace to System.err, the error output stream. public StackTraceElement getStackTrace () Returns an array containing each element of the stack trace. The element at index 0 represents the top of the call stack and the last element of the array represents the method at the bottom of the call stack. public Throwable fillInStackTrace () Fills the stack trace for this Throwable object with the current stack trace, adding to all previous information in the stack trace. Example Here is the sample code using some of the methods given above - Live demo class Example {static void main (String args) {try {def arr = new int [3]; arr [5] = 5; } catch (ArrayIndexOutOfBoundsException ex) {println (ex.toString ()); println (e.g. getMessage ()); println (ex.getStackTrace ()); } catch (Exception ex) {println ( "Catch exception "); } finally {println ( "The final block "); } println ( "Let"s move on after the exception "); }} When we run the above program, we will get the following result - java.lang.ArrayIndexOutOfBoundsException: 5 5 [org.codehaus .groovy.runtime.dgmimpl.arrays.IntegerArrayPutAtMetaMethod $ MyPojoMetaMet hodSite.call (IntegerArrayPallodeAtMeta:Metimehaus.groovy.grays.juntime.java.java . 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.ava.rebectava:60:60 ), org.codehaus.groovy.reflection.CachedMethod.invoke (CachedMethod.java:93), groovy.lang.MetaMethod.doMethodInvoke (MetaMethod.java:325), groovy.lang. .lang.GroovyShell.run (GroovyShell.run : 524), groovy.lang.GroovyShell.run (GroovyShell.java:513), groovy.ui.GroovyMain.processOnce (GroovyMain.java:652), groovy.ui.Groovain. run (GroovyMain.java:384), groovy.ui.GroovyMain.process (GroovyMain.java:370), groovy.ui.GroovyMain.processArgs (GroovyMain.java:129), groovy.ui .GroovyMain.main (GroovyMain. 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.DelccesslessAccesslessMethodetAre .Method.invoke (Method.java:606), com.intellij.rt.execution.application.AppMain.main (AppMain.java:144)] The last block Let"s continue after the exception