Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Groovy - Exception Handling

11. Exception Handling

Exception handling is a crucial aspect of any programming language, including Groovy. Exceptions are runtime errors that can occur during program execution. Groovy provides a robust mechanism for handling exceptions to ensure that your programs can gracefully recover from errors.

Types of Exceptions in Groovy:

Groovy, like Java, has a hierarchy of exception classes. The base class for all exceptions is 'java.lang.Exception'. Some common exception types in Groovy include:

  1. 'java.lang.Exception': The base class for all exceptions.
  2. 'java.lang.RuntimeException': The base class for runtime exceptions.
  3. Custom Exception Classes: You can create your own exception classes by extending 'java.lang.Exception' or its subclasses.

The'try-catch'Block:

In Groovy, you can handle exceptions using a 'try-catch' block. This block allows you to specify code that might throw an exception and then provide one or more 'catch' blocks to handle those exceptions.

Syntax:
try {
    // Code that might throw an exception
} catch (ExceptionType1 e1) {
    // Handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Handle ExceptionType2
} finally {
    // Optional: Code that runs regardless of whether an exception occurred or not
}
 
Example:
try {
    def result = 10 / 0 // This will throw an ArithmeticException
} catch (ArithmeticException e) {
    println("An arithmetic error occurred: ${e.message}")
} finally {
    println("Cleanup code: This always runs")
}
 

In this example, we catch an 'ArithmeticException' that occurs when dividing by zero, and we  also have a 'finally' block that executes regardless of whether an exception occurred or not.

The'throw'Statement:

You can manually throw exceptions using the 'throw' statement. This is useful when you want to create custom exceptions or handle specific error cases.

Example:
def age = -5

try {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative")
    }
    println("Age is valid: $age")
} catch (IllegalArgumentException e) {
    println("Invalid age: ${e.message}")
}
 

In this example, we manually throw an 'IllegalArgumentException' if the age is negative.

Handling Multiple Exceptions:

You can handle multiple exceptions by adding multiple 'catch' blocks for different exception types.

Example:
try {
    // Code that might throw exceptions
} catch (IOException e) {
    // Handle IOException
} catch (IllegalArgumentException e) {
    // Handle IllegalArgumentException
}
 

Using'catch'Blocks Without Exception Variables:

You can use 'catch'blocks without specifying an exception variable if you don't need to access the exception object.

Example:
try {
    // Code that might throw an exception
} catch (ExceptionType) {
    // Handle the exception without accessing the exception object
}
 

Custom Exception Classes:

You can create custom exception classes by extending 'java.lang.Exception'or its subclasses. This is helpful for creating meaningful and specific exceptions for your application.

Example:
class MyCustomException extends Exception {
    MyCustomException(String message) {
        super(message)
    }
}

try {
    throw new MyCustomException("This is a custom exception")
} catch (MyCustomException e) {
    println("Caught custom exception: ${e.message}")
}
 

In this example, we define a custom exception class 'MyCustomException'and throw an instance of it in the 'try' block.

Conclusion:

Exception handling is an essential part of writing robust and reliable Groovy programs. By using 'try-catch' blocks and understanding the different exception types, you can gracefully handle errors, log relevant information, and ensure that your application continues to run smoothly even in the presence of unexpected issues. Custom exception classes allow you to create expressive and specific error messages for your application's needs.