
- Groovy Tutorial
- Groovy - Home
- Groovy - Overview
- Groovy - Environment
- Groovy - Basic Syntax
- Groovy - Data Types
- Groovy - Variables
- Groovy - Optionals
- Groovy - Numbers
- Groovy - Strings
- Groovy - Ranges
- Groovy - Lists
- Groovy - Maps
- Groovy - Dates & Times
Groovy Operators
- Groovy - Operators
- Groovy - Arithmetic Operators
- Groovy - Assignment Operators
- Groovy - Relational Operators
- Groovy - Logical Operators
- Groovy - Bitwise Operators
- Groovy - Spaceship Operator
- Groovy - in Operator
- Groovy - Elvis Operator
- Groovy - Safe Navigation Operator
- Groovy Operator Precedence & Associativity
Control Statements
- Groovy - Decision Making
- Groovy - If Else Statement
- Groovy - Switch Statement
- Groovy - Loops
- Groovy - For Loop
- Groovy - For-in Loop
- Groovy - While Loop
- Groovy - Do While Loop
- Groovy - Break Statement
- Groovy - Continue Statement
Groovy File Handling
- Groovy - File I/O
- Java - Create a File
- Java - Write to File
- Java - Append to File
- Java - Read Files
- Java - Delete Files
- Java - File Properties
- Java - File Existence and Type
- Java - File Size
- Java - File Permissions
- Java - Directories
- Java - Listing Directories
- Java - Filtering Files/Directories
- Java - Deleting Directories
- Java - Renaming Files/Directories
Groovy Error & Exceptions
- Groovy - Exception Handling
- Groovy - try-catch Block
- Groovy - try-with-resources
- Groovy - Multi-catch Block
- Groovy - Nested try Block
- Groovy - Finally Block
- Groovy - throw Exception
- Groovy - Exception Propagation
- Groovy - Built-in Exceptions
- Groovy - Custom Exception
Groovy Multithreading
- groovy - Multithreading
- groovy - Thread Life Cycle
- groovy - Creating a Thread
- groovy - Starting a Thread
- groovy - Joining Threads
- groovy - Naming Thread
- groovy - Thread Scheduler
- groovy - Thread Pools
- groovy - Main Thread
- groovy - Thread Priority
- groovy - Daemon Threads
- groovy - Shutdown Hook
Groovy Synchronization
- groovy - Synchronization
- groovy - Block Synchronization
- groovy - Static Synchronization
- groovy - Inter-thread Communication
- groovy - Thread Deadlock
- groovy - Interrupting a Thread
- groovy - Thread Control
- groovy - Reentrant Monitor
- Groovy - Methods
- Groovy - Methods
- Groovy - Optional parenthesis
- Groovy - Named Arguments
- Groovy - Closures as Arguments
- Groovy - Method Overloading
- Groovy - Method Scope and Visibility
- Groovy - isCase Method
- Groovy - Implicit Return
- Groovy - Variable Arguments
- Groovy - Regular Expressions
- Groovy - Regular Expressions
- Groovy - Defining Regular Expressions
- Groovy - Matcher Object
- Groovy - Regex Tasks
- Groovy - XML
- Groovy - XML
- Groovy - Parsing XML
- Groovy - Creating XML
- Groovy - Modifying XML
- Groovy - Querying XML
- Groovy - Simplified Notation
- Groovy - Closure based Querying
- Groovy - Closure based Creation
- Groovy - JSON
- Groovy - JSON
- Groovy - Parsing JSON
- Groovy - Creating JSON using JsonOutput
- Groovy - Creating JSON using JsonBuilder
- Groovy - Modifying JSON
- Groovy - Error Handling
- Groovy - Handling JSON Arrays
- Groovy - JSON Array Operations
- Groovy - JSON Objects
- Groovy - JSON Object Operations
- Groovy - Generics
- Groovy - Generics
- Groovy - Declaring Generic Types
- Groovy - Bound Type Parameters
- Groovy - Wild Cards
- Groovy - Miscellaneous
- Groovy - Object Oriented
- Groovy - Closures
- Groovy - Annotations
- Groovy - JMX
- Groovy - DSLS
- Groovy - Database
- Groovy - Builders
- Groovy - Command Line
- Groovy - Unit Testing
- Groovy - Template Engines
- Groovy - Meta Object Programming
- Groovy Useful Resources
- Groovy - Quick Guide
- Groovy - Useful Resources
- Groovy - Discussion
Groovy - try catch block
An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
Groovy try and catch
A method catches an exception using a combination of the try and catch keywords. A try and catch block is placed around the code that might generate an exception. Code within a try and catch block is referred to as protected code, and the syntax for using try/catch looks like the following −
The try Block
The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.
The catch Block
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Syntax of Groovy try and catch Block
try { // Protected code } catch (ExceptionName e1) { // Catch block }
Example - Groovy try and catch Block
In following example, an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception. As we've enclosed the code with a try block, this exception can be handled within next catch block which we've declared to catch ArrayIndexOutOfBoundsException. After catching the exception, we can take the corresponding action. Here we're printing the details of the exception thrown.
Example.groovy
class Example { static void main(String[] args) { try { int[] a = new int[2]; println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { println("Exception thrown :" + e); } println("Out of the block"); } }
Output
This will produce the following result−
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2 Out of the block
Multiple Catch Blocks With Groovy Try
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following −
Syntax: Multiple Catch Blocks
try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }
The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.
Example - Multiple Catch Blocks
Here is code segment showing how to use multiple try/catch statements. In this example, we're creating an error by dividing a value by 0. As it is not an ArrayIndexOutOfBoundsException, next catch block handles the exception and prints the details.
Example.groovy
class Example { static void main(String[] args) { try { int[] a = new int[2]; int b = 0; int c = 1/b; println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { println("ArrayIndexOutOfBoundsException thrown :" + e); }catch (Exception e) { println("Exception thrown :" + e); } println("Out of the block"); } }
Output
This will produce the following result−
Exception thrown :java.lang.ArithmeticException: / by zero Out of the block
Catching Multiple Exceptions with Groovy Try and Catch Block
you can handle more than one exception using a single catch block, this feature simplifies the code. Here is how you would do it −
Syntax: Catching Multiple Exceptions
catch (IOException | FileNotFoundException ex) { logger.log(ex); throw ex;
Example - Catching Multiple Exceptions
Here is code segment showing how to use multiple catch in a single statement. In this example, we're creating an error by dividing a value by 0. In single statement, we're handling ArrayIndexOutOfBoundsException and ArithmeticException.
Example.groovy
class Example { static void main(String[] args) { try { int[] a = new int[2]; int b = 0; int c = 1/b; println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException | ArithmeticException e) { println("Exception thrown :" + e); } println("Out of the block"); } }
Output
This will produce the following result−
Exception thrown :java.lang.ArithmeticException: / by zero Out of the block