TRY ... CATCH
- Last UpdatedFeb 18, 2025
- 2 minute read
TRY ... CATCH provides a way to handle some or all possible errors that may occur in a given block of code, while still running rather than terminating the program. The TRY part of the code is known as the try block. Deal with any exceptions in the CATCH part of the code, known as the catch block.
The general format for TRY ... CATCH is as follows:
TRY
[try statements] ’guarded section
CATCH
[catch statements]
ENDTRY
Where:
tryStatements
Statement(s) where an error can occur. Can be a compound statement. The tryStatement is a guarded section.
catchStatements
Statement(s) to handle errors occurring in the associated Try block. Can be a compound statement.
Statements inside the Catch block may reference the reserved ERROR variable, which is a .NET System.Exception thrown from the Try block. The statements in the Catch block run only if an exception is thrown from the Try block.
TRY ... CATCH is executed as follows:
-
Run-time error handling starts with TRY. Put code that might result in an error in the try block.
-
If no run-time error occurs, the script will run as usual. Catch block statements will be ignored.
-
If a run-time error occurs, the rest of the try block does not execute.
-
When a run-time error occurs, the program immediately jumps to the CATCH statement and executes the catch block.
The simplest kind of exception handling is to stop the program, write out the exception message, and continue the program.
The error variable is not a string, but a .NET object of System.Exception. This means you can determine the type of exception, even with a simple CATCH statement. Call the GetType() method to determine the exception type, and then perform the operation you want, similar to executing multiple catch blocks.
Example:
dim command = new System.Data.SqlClient.SqlCommand;
dim reader as System.Data.SqlClient.SqlDataReader;
command.Connection = new System.Data.SqlClient.SqlConnection;
try
command.Connection.ConnectionString = "Integrated Security=SSPI";
command.CommandText="select * from sys.databases";
command.Connection.Open();
reader = command.ExecuteReader();
while reader.Read()
me.name = reader.GetString(0);
LogMessage(me.name);
endWhile;
catch
LogMessage(error);
endtry;
if reader <> null and not reader.IsClosed then
reader.Close();
endif;
if command.Connection.State == System.Data.ConnectionState.Open then
command.Connection.Close();
endif;
Note: The proceeding code example uses the System.Data.SqlClient method, which is deprecated. Instead of this, use the SQLData Script Library for SQL Server queries.