Skip to content
Exception Handling and Elvis
step 1/5

Reading — step 1 of 5

Learn

~1 min readBeans and Errors

Groovy uses Java's exception model but smooths the surface.

Standard try/catch:

try {
    def n = Integer.parseInt(input)
    process(n)
} catch (NumberFormatException e) {
    println "bad number: ${e.message}"
} catch (Exception e) {
    println "unexpected: ${e}"
} finally {
    cleanup()
}

Multi-catch (Groovy supports it):

try { ... }
catch (NumberFormatException | IllegalArgumentException e) { ... }

Groovy's null handling helpers:

Safe navigation ?. — null-safe property/method access:

def len = name?.length()      // null if name is null
def city = user?.address?.city

Elvis ?: — provide default for null/falsy:

def display = name ?: "anonymous"
def count = list ?: []         // empty list if null

Combine for null-safe with default:

def len = name?.length() ?: 0

Truthiness in Groovy — these are FALSY:

  • null
  • 0, 0.0
  • empty String
  • empty Collection or Map
  • empty array

Everything else is truthy. So if (list) works whether list is null OR empty.

Groovy unchecked exceptions — checked exceptions don't have to be declared. throws clauses are optional. Reduces Java's verbosity.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…