Documentation
Back to website >

try...catch...finally (JScript)

The "try...catch....finally" statement allows you to react to errors in a structured manner.

Script code, which can cause a runtime error, dresses a try-catch statement. If a runtime error occurs within the try block, it is not displayed by the runtime system, but is branched into the catch block. The programmer can now check the exact cause of the error and react to it.

The finally block is always executed if it exists. It does not matter whether an error has occurred in the try block or not. The only exception is when an error occurs but no catch block exists. In this case, a normal runtime error is raised.

Syntax

try 
  {tryInstruction}
catch(Variable)
  {catchInstruction}
finally
  {finallyInstruction}

Excample 1

An example for try...catch.

var
  Yesterday, Tomorrow, Toda;

Toda=3;

try
  {
    Yesterday=Toda-1;
    Tomorrow=Today+1;
  }
catch (e)
  {
    Result="Assigning Error! Reason: "+e
  }

In this example, an assignment "Tomorrow=Today+1" is executed in the try block. However, due to a typing error, the variable "Today" is not defined. Normally, an object error would be reported in this case. However, since the statement is executed in a try block, the execution branches to the catch block. There an error text is assigned to the result variable.

The original error text is contained in the variable "e" and is appended to the result variable.

Since the error in the try block only occurred in the second block line, the line "Yesterday=Toda-1" is still executed correctly.

Excample 2

A simple example of try...catch..finally.

var
  Yesterday, Tomorrow, Toda;

Toda=3;

try
  {
    Yesterday=Toda-1;
    Tomorrow=Today+1;
  }
catch (e)
  {
    Result="Assigning Error! Reason: "+e
  }
finally
  {
    Toda=1;
  }

This is an extension for example. At the end of the try...catch the finally block is executed. This sets the variable "Today" to the value 1 in any case, regardless of whether an error has occurred in the try block or not.

Excample 3

A simple example of try...finally.

var
  Yesterday, Tomorrow, Toda;

Toda=3;

try
  {
    Yesterday=Toda-1;
    Tomorrow=Today+1;
  }
finally
  {
    Toda=1;
  }

The finally block is not executed here as the only exception. Since an error occurs in the try block, but no catch block exists, the script is terminated directly at the error location and a runtime error is displayed.