- 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 - Error Handling While Processing JSON
Handling error is a crucial aspect of any robust application. Groovy provides groovy.json.JsonException specially to handling error which can occur while parsing an exception using JsonSlurper object to parse a JSON string. Apart from parsing errors, we should handle other scenarios using standard try-catch functionality of Groovy. Following are common use cases with corresponding Exception where errors can come up while processing a JSON.
JsonException − To handle parsing errors while parsing JSON using JsonSlurper.
MissingPropertyException − To handle a access to non-existing key of object parsed from JSON.
IndexOutOfBoundsException − To handle a invalid index in case of JSON array.
NullPointerException − To handle issue while accessing properties of a null object
NumberFormatException − To handle error while converting a value while using JsonBuilder.
Example - Handling Parsing errors while processing JSON
While using JsonSlurper it is good practice to wrap the parseText method under try-catch block for JsonException as shown in example below −
Example.groovy
import groovy.json.JsonSlurper
import groovy.json.JsonException
def badJsonString = '''
{
"name": "Alice",
"age": 30,
"city": New York // Missing quotes
}
'''
def jsonSlurper = new JsonSlurper()
try {
def jsonData = jsonSlurper.parseText(badJsonString)
println jsonData
} catch (JsonException e) {
println "Parsing error while processing JSON: ${e.getMessage()}"
}
Output
When we run the above program, we will get the following result.
Parsing error while processing JSON: Unable to determine the current character, it is not a string, number, array, or object The current character read is 'N' with an int value of 78 Unable to determine the current character, it is not a string, number, array, or object line number 5 index number 45 "city": New York // Missing quotes ..........^
Example - Handling errors while creating JSON
While using JsonBuilder, we may face exceptions while processing the data programming, It is advisable to put try-catch with relevant exception as shown in example below −
Example.groovy
import groovy.json.JsonBuilder
def data = [name: "Charlie", age: "fortyfive"]
try {
def builder = new JsonBuilder()
builder {
name data.name
age data.age.toInteger() // toInteger will throw error
}
println builder.toPrettyString()
} catch (NumberFormatException e) {
println "Error: Age is not a valid number - ${e.getMessage()}"
}
Output
When we run the above program, we will get the following result.
Error: Age is not a valid number - For input string: "fortyfive"
Example - Handling errors while processing JSON data after parsing
It is always a good practice to handle scenarios even after parsing JSON like missing property, null object acess, invalid index access and so as shown in example below −
Example.groovy
import groovy.json.JsonSlurper
def jsonString = '''
{
"name": "A;ice",
"age": 25,
"hobbies": ["reading books","listening music"]
}
'''
def slurper = new JsonSlurper()
def person = slurper.parseText(jsonString)
try {
println "Name: ${person.name}"
println "City: ${person.city}"
// MissingPropertyException can occur if hobbies in not present
println "First hobby: ${person.hobbies[0]}"
// IndexOutOfBoundsException may occur if index is out of bound
println "Second hobby: ${person.hobbies[1]}"
// NullPointerException in case address is null
println "Address zip: ${person.address.zip}"
} catch (MissingPropertyException e) {
println "Property missing - ${e.getProperty()}"
} catch (IndexOutOfBoundsException e) {
println "Invalid Index - ${e.getMessage()}"
} catch (NullPointerException e) {
println "Null Propery Accessed - ${e.getMessage()}"
}
Output
When we run the above program, we will get the following result.
Name: A;ice City: null First hobby: reading books Second hobby: listening music Null Propery Accessed - Cannot get property 'zip' on null object