Introduction to SQLSQL DatabaseSQL DatatypesSQL QueriesSQL DML StatementsSQL Constraints and IndexingSQL FunctionsStored Procedure and Triggers
SQL provides mechanisms to handle errors gracefully using TRY...CATCH
blocks (in SQL Server, PostgreSQL, and other relational databases that support it). This allows developers to capture and handle runtime errors in a controlled manner.
TRY…CATCH
The TRY...CATCH
structure is used to catch exceptions and handle errors in SQL code. If an error occurs in the TRY
block, control is passed to the CATCH
block, where you can log the error or perform alternative actions.
Syntax:
BEGIN TRY
-- SQL statements that might cause errors
END TRY
BEGIN CATCH
-- Error handling code
SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
Example: Handling a division by zero error.
BEGIN TRY
-- Example operation that could fail
SELECT 10 / 0 AS Result;
END TRY
BEGIN CATCH
-- Catch the error and display a message
SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
In this example, the division by zero error will be caught, and a user-friendly error message will be returned.
Error Functions in SQL
SQL provides several built-in functions to retrieve error information in the CATCH
block:
ERROR_MESSAGE()
: Returns the error message.ERROR_NUMBER()
: Returns the error number.ERROR_SEVERITY()
: Returns the severity of the error.ERROR_STATE()
: Returns the error state.
Example:
BEGIN TRY
-- Code that may cause an error
SELECT 1 / 0;
END TRY
BEGIN CATCH
SELECT
ERROR_MESSAGE() AS ErrorMessage,
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity;
END CATCH;