begin Try -- endbegin--SQL (handle error action)end Catch
We're going to write the SQL that might go wrong between the begin try...end try, and if something goes wrong, just the program jumps to the beign catch...end catch immediately following the begin Try...end try and executes beign catch...end cat CH Error Handling SQL. Try: Catch can be nested. In the begin catch ... end catch we can get the error message using the following four functions provided by the system:
Error_number return error code
Error_serverity returns the severity level of the error
Error_state Return Error status code
Error_message returns the complete error message
The above four functions at the same begin catch ... end catch can be used more than once, and the value is constant.
Here is a simple little example.
begin Try Select 2 / 0 End Try begin Catch Select as as as as Error_severity end catch
Results:
-----
Error_number error_message error_state error_severity
8134 encountered a divisor error with zero. 1 16
-------------------------------------------------------
Not affected by TRY ... Errors affected by CATCH construction
TRY ... Catch constructs do not catch errors in the following situations:
A warning or informational message with a severity level of 10 or less.
Errors that are handled by the SQL Server Database Engine task that has a severity level of 20 or higher and terminates the session. If the severity level of the error that occurred is 20 or higher, and the database connection is not interrupted, TRY ... CATCH will handle the error.
A message that needs attention, such as a client interrupt request or a client connection outage.
When the system administrator uses the KILL statement to terminate the session.
UseAdventureWorks;GOBEGINTRY--Generate a divide-by-zero error. SELECT 1/0;ENDTRYBEGINCATCHSELECTerror_number () aserrornumber, error_severity () aserrorseverity, error_state () aserrorstate, Error_procedure () aserrorprocedure, Error_line () asErrorLine, Error_message () aserrormessage;ENDCATCH;GO
UseAdventureWorks;GOBEGIN TRANSACTION; BEGINTRY--Generate a constraint violation error. DELETE fromproduction.productWHEREProductID= 980;ENDTRYBEGINCATCHSELECTerror_number () aserrornumber, error_severity () aserrorseverity, error_state () aserrorstate, Error_procedure () aserrorprocedure, Error_line () asErrorLine, Error_message () aserrormessage; IF @ @TRANCOUNT > 0 ROLLBACK TRANSACTION;ENDCATCH;IF @ @TRANCOUNT > 0 COMMIT TRANSACTION;GO
Source text:
52651660
Extract of SQL Server exception handling mechanism (Begin try begin Catch)