Error handling using try and catch

Handling errors is an important issue when creating processes and BI# provides an elegant way for dealing with typical situations. Use the try statement to enclose a list of statements that might raise an error. Then use the catch statement to deal with those errors. Here is an example:

#define EngineVersion 5.0
#define RuntimeVersion 5.0

void ExceptionHandlingDemo(int x)
@Description: "Demonstrates how to use the try/catch statements.";
@Category: "Demo";
{
     string errorMessage = "";
     int errorCode = 0;

     // You can raise and catch your own errors.    
     try
     {
          if (x > 10)
          {
              RaiseError("x has to be less or equal 10!", 1);
          }
          WriteLine(x);
     }
     catch (errorMessage, errorCode)
     {
          WriteLine(errorMessage);
          WriteLine(errorCode);
     }
}

This process expects an int parameter named x and checks if it is less or equal 10. If not, the process raises an error through the RaiseError function. This function accepts an error message and an error code that you can define yourself.

Note: Note that the error code has to be greater or equal zero.

Process execution continues with the catch statement. The process does not execute the WriteLine(x) statement. Instead, it outputs the error message and the error code. Both the message and the code are assigned automatically to the variables errorMessage and errorCode. You can freely choose their names, but you must declare them explicitly and they must be of types string and int.

Errors not only occur in your own code. They might also occur in the BI# runtime functions. For example, an error is raised, when you try to connect to a database with an invalid connection string. You can handle this kind of error in the same way you handle errors raised in your code:

#define EngineVersion 5.0
#define RuntimeVersion 5.0

void ExceptionHandlingDemo()
@Description: "Demonstrates how to use the try/catch statements.";
@Category: "Demo";
{
     string errorMessage = "";
     int errorCode = 0;

     // You can catch errors raised by runtime functions.
     try
     {
          SQLConnection connection = SQLCreateConnection("");
     }
     catch (errorMessage, errorCode)
     {
          WriteLine(errorMessage);
          WriteLine(errorCode); // Will be -1 in case of runtime errors.
     }
}

As in the sample before, you receive an error message and an error code. The only difference is that the error code is -1 in case of errors raised by a runtime function.