|
|
Many scripting calls throw exceptions when a runtime error occurs. As the programmer, you should check for exceptions in code and handle them before a runtime error is displayed to the user, either by resolving the condition that caused the error and continuing program execution, or by ending execution gracefully.
To handle an exception, place the code that may throw an exception in a try block, followed by a catch block. If an exception is thrown within a try block, execution is immediately redirected to the catch block, where you can put code to correct the error or end execution. If an exception occurs and there is no try block, a runtime error occurs, halting execution.
When an exception is thrown, an object of type Error is passed to the catch block. The Exception object has two properties: the object property, which indicates what type of object threw the exception, and the description property, which returns a string describing the cause of the exception. You can use this object to get information about the exception.
In addition to the try and catch blocks, your exception handling code can include an optional finally block. The code in the finally block will always be executed, whether or not an exception was thrown. If an exception occurs, the code in the finally block will be executed after the code in the catch block.
The following example demonstrates a simple exception handler:
try
{
var rs = Table.select("MyTable", "*");
}
catch(e)
{
Script.Log("Database Exception:", "Thrown by: "
+ e.object + ", Description: " + e.description);
}
finally
{
Script.Log("Exiting now.");
}
|