Overview of exceptions

Gosu supports the full feature set for Java exception handling, including try/catch/finally blocks. However, unlike Java, no exceptions are checked. Standard Gosu style is to avoid checked exceptions where possible. You can throw any exception in Gosu, but if the exception is not a RuntimeException, Gosu wraps the exception in a RuntimeException.

Catching exceptions

The following Gosu code is a simple try/catch/finally:

try {
  user.enter(bar)
} catch (e : Exception) {
  print("Failed to enter the bar!")
} finally {
  // Clean-up code here...
}

To catch only specific exceptions, specify a subclass such as IOException instead of Exception. For example:

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

Throwing exceptions

In Gosu, throw an exception with the throw statement, which is the throw keyword followed by an object. The following example creates an explicit RuntimeException exception:

if (user.Age < 21) {
  throw new RuntimeException("User is not allowed in the bar")
}

You can also pass a non-exception object to the throw statement. If you pass a non-exception object, Gosu first coerces it to a String. Next, Gosu wraps the String in a new RuntimeException, which has a Message property that contains the String data. Your error-handling code can use the Message property for logging or displaying messages to users.

You could rewrite the previous throw code example as the concise code:

if (user.Age < 21) {
  throw "User is not allowed in the bar"
}