This recipe introduces three usages that are rather advantageous and important, try, catch, and finally functions.
We need a new workflow and a scriptable task inside it to try these out.
The example workflow, 06.02 JavaScript special statements
, contain all the following examples.
There are two sections in this recipe.
When writing any code, you want to make sure that when the code produces an error, you are still able to execute some critical operations, such as closing an open connection:
try { //Main code; System.log("Start Main"); if (error) { throw("Create Error"); } System.log("End Main"); } catch( ex ) { // error handling System.log("Error: "+ex); } finally { //Final Part System.log("Finally"); }
throw
statements create an intentional error). Without an error, the main code (try
) would be executed and then the finally
code. When an error is thrown in the main code, the execution (try
) will be stopped before "End Main"
and then will execute the catch
code followed by the finally
code.The function
command enables us to repeat a program code. A function needs to be defined before it is used, which means that it is placed at the beginning of a program:
function functionName (parameter1, parameter2) { // program example parameter3 = parameter1 + parameter2 return parameter3 }
result = functionName(2,3);
The call will put the value 2
into parameter1
and the value 3
into parameter2
of the functionName
function. The result
variable will contain the return value of the function.
A typical example where try
/catch
/finally
is used; is to make sure an open connection to a database is closed if an error occurs. Open connections can cause servers to perform slower, rendering them more vulnerable to intrusion or even corrupt data. You would open the connection in the try
section and write the close function in the finally
section.
If try
, catch
, and finally
are used, you would place the function before the try
command. A function is similar to the way an action works. We discussed actions in the recipe Creating actions in this chapter.