Catching exceptions

Gosu allows you to catch all general exceptions, or test for and catch specific types of exceptions.

The standard syntax for catch is the following, which catches all exceptions by specifying the class Exception:

catch (e : Exception)

To catch a single specific exception type, specify a subclass such as IOException instead of Exception. The technique of catching a named exception is called checked exceptions. The recommended Gosu coding style is not to use checked exceptions, although this technique is supported.

The following code is an example of checked exceptions:

try {
  doSomething()
}
catch (e : IOException) {
  // Handle the IOException
}

Add a finally block at the end to perform cleanup code that runs for both error and success code paths:

try {
  doSomething()
}
catch (e : IOException) {
}
finally {
  // PERFORM CLEANUP HERE
}

Throwable

The class Throwable is the superclass of all errors and exceptions in the Java language. Best practice is to catch Exception, not Throwable. Use catch(e : Exception) not catch(e : Throwable). Catching Throwable can catch serious infrastructure problems like OutOfMemoryException or AssertionFailedException. Typical code cannot handle those types of exceptions, so catch Exception so that these serious infrastructure exceptions propagate upward.