Throwing exceptions
The throw
statement generates an error condition that you can handle through the
use of try/catch/finally blocks.
Warning: Do not use
throw statements as part of regular
non-error program flow. Use these statements only for handling actual
error conditions.The following example throws 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"
}
Syntax
throw <expression>In the following example,
notice how the error message changes if the value of x changes from 0 to 1.
Example
uses java.lang.Exception
doOuterCode() // Call outer code
function doOuterCode() {
try {
doInnerCode(0)
doInnerCode(1)
}
catch (e : Exception) {
print( e.Message + " -- caught in OUTER code" )
}
}
function doInnerCode(x : int) {
print("For value ${x}...")
try {
if ( x == 0 ) {
throw "x equals zero"
} else {
throw "x does not equal zero"
}
}
catch (e : Exception) {
if ( e.Message == "x equals zero" ) {
print(e.Message + " -- caught in INNER code")
} else { throw e }
}
}
This example prints:
For value 0...
x equals zero -- caught in INNER code.
For value 1...
x does not equal zero -- caught in OUTER code