Handling exceptions with try/catch/finally

The try/catch/finally blocks provides a way to handle some or all of the possible errors that may occur in a given block of code during run time. If errors occur that the script does not handle, Gosu provides its normal error message, as if no error handling existed.

The try block contains code where an error can occur, while the catch block contains the code to handle any error that does occur:

  • If an error occurs in the try block, Gosu passes program control to the catch block to handle the error.
  • In the catch block, Gosu passes as an argument to catch block a value that represents the exception that occurred in the try block. If an error is thrown from Java code, the value that the catch block gets is the exception thrown. For exceptions directly thrown from Gosu code, any value that is not a subclass of RuntimeException is wrapped in a RuntimeException object.
  • If no error occurs, Gosu does not execute the catch block.
  • If the error cannot be handled in the catch block associated with the try block where the error occurred, use the throw statement. The throw statement rethrows the exception to a higher-level error handler.

After Gosu runs all statements in the try block or after running the error handling code in the catch block, Gosu runs the finally block.

Gosu executes the code inside the finally block, even if a return statement occurs inside the try or catch blocks, or if an error is thrown from a catch block. It is important to understand that , Gosu always runs the finally block.

In a finally block, Gosu does not permit the return, break, or continue statements.

Syntax

try 
  <try statements>
[catch ( exception )
  <catch statements>]
[finally
  <finally statements>]

Example

try {
  print( "Outer TRY running..." )
  try {
    print( "Nested TRY running..." )
    throw "an error"
  } 
  catch (e : Exception) {
    print( "Nested CATCH caught "+e )
    throw e + " rethrown"
  } 
  finally { print( "Nested FINALLY running..." ) }
} 
catch (e : Exception) { print( "Outer CATCH caught " + e ) }
finally { print( "Outer FINALLY running" ) }

Output

Outer TRY running...
Nested TRY running...
Nested CATCH caught gw.lang.parser.EvaluationException: an error
Nested FINALLY running...
Outer CATCH caught gw.lang.parser.EvaluationException: gw.lang.parser.EvaluationException: an error 
        rethrown
Outer FINALLY running

See also