6. Exceptions

Exception handling in Golo is simple. There is no distinction between checked and unchecked exceptions.

6.1. Raising exceptions

Golo provides 2 predefined functions for raising exceptions:

  • raise(message) throws a java.lang.RuntimeException with a message given as a string, and
  • raise(message, cause) does the same and specifies a cause which must be an instance of java.lang.Throwable.

Throwing an exception is thus as easy as:

if somethingIsWrong() {
  raise("Woops!")
}

6.2. Raising specialized exceptions

Of course not every exception shall be an instance of java.lang.RuntimeException. When a more specialized type is required, you may simply instantiate a Java exception and throw it using the throw keyword as in the following example:

module golotest.execution.Exceptions

import java.lang.RuntimeException

function runtimeException = {
  throw RuntimeException("w00t")
}

6.3. Exception handling

Exception handling uses the familiar try / catch, try / catch / finally and try / finally constructions. Their semantics are the same as found in other languages such as Java, especially regarding the handling of finally blocks.

The following snippets show each exception handling form.

# Good old try / catch
try {
  something()
} catch (e) {
  e: printStackTrace()
}

# A try / finally
try {
  doSomething()
} finally {
  cleanup()
}

# Full try / catch / finally construct
try {
  doSomething()
} catch (e) {
  e: printStackTrace()
  case {
    when e oftype IOException.class {
      println("Oh, an I/O exception that I was expecting!")
    }
    when e oftype SecurityException.class {
      println("Damn, I didn't expect a security problem...")
      throw e
    }
    otherwise {
      throw e
    }
  }
} finally {
  cleanup()
}

Tip

Because Golo is a weakly typed dynamic language, you need to check for the exception type with the oftype operator. In a statically typed language like Java, you would instead have several catch clauses with the exception reference given a specific type. We suggest that you take advantage of the case branching statement.