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 a
simple example:
#define EngineVersion 3.0 #define RuntimeVersion 3.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 by using the
RaiseError
function. This function accepts an error
message and an error code that you can define yourself.
Process execution will continue with the
catch
statement, that is, the process will not execute
the
WriteLine(x)
statement. Instead, it will output 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
have to declare them explicitly and they have to be of types
string
and
int
.
Errors will not only occur in your own code. They might also occur in the BI# runtime functions. For example, an error will be raised, when you try to connect to a database by using an invalid connection string. You can handle this kind of error in the same way you handle errors raised in your code:
#define EngineVersion 3.0 #define RuntimeVersion 3.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 will be -1 in case of errors raised by a runtime function.