try

The try keyword executes control statements.

Purpose

The try keyword is used to execute control statements with the ability to predeclare named exception handlers. A catch statement specifies exceptions that are caught if thrown within a try block. A finally statement specifies a control block that is executed after a try block is finished processing, including its exceptions, if any.

Context

Functions or rule actions

Syntax

try {statements} 
catch (exceptionType1 identifier) {statements} 
[catch (exceptionType2 identifier) {statements} 
...]
finally {statements}

Description

Use try-catch-finally statements in the action part of rules or in functions. Such statements define a block of code for exception handling. The try, catch, and finally blocks all begin and end with curly braces.

The try block must be followed by at least one catch or a finally statement, or both. The try statement governs the statements enclosed within it and defines the scope of any exception handlers associated with it.

The catch statements are designed to handle a specific type of exception. The code within a catch statement is executed if an exception is caught. The exceptionType parameters declared in the catch statement specify the type of exception that the statement can handle and also provide identifiers that the catch statement can use to refer to the exception object that it is handling. The identifier must be of type Throwable or one of its subclasses.

The finally statement is guaranteed to be executed if any portion of the try statement is executed, regardless of how the code in the try and catch statements completes.

Example

Example 1

In this example, the division rule includes a try statement in its action part. When the ?x variable is equal to zero, the division throws an ArithmeticException. The exception is caught by the catch clause which prints a message.

rule division { 
   when {
      ?x = Integer() ;
      ?y = Integer() ;
   }
   then {
      try { 
         int ?z = ?y/?x;
      }
      catch (ArithmeticException e) {
         System.out.println("Exception message : " + e) ;
      }
   }
}
Example 2

This example describes two catch statements, with one handler for each of the two types of exceptions that can be thrown within the try block: ArrayIndexOutOfBoundsException and IOException. When an exception occurs, the first catch statement that has an exception type compatible with the thrown exception is executed.

try {
    ... 
} 
catch (ArrayIndexOutOfBoundsException e) {
   System.err.println("Caught ArrayIndexOutOfBoundsException: "
                      + e);
} 
catch (IOException e) {
   System.err.println("Caught IOException: " + e);
}
Example 3

This example shows a finally statement.

try{
...
}
finally {
      note("in finally");
}