Definitions of Each Function
ERROR_NUMBER()
:
- Definition: Returns the error number of the last error that occurred.
- Usage: Useful for identifying the specific error that was raised.
ERROR_MESSAGE()
:
- Definition: Returns the message text of the error that caused the CATCH block to execute.
- Usage: Provides a human-readable description of the error.
ERROR_SEVERITY()
:
- Definition: Returns the severity level of the error that caused the CATCH block to execute.
- Usage: Indicates the severity of the error, which can help in determining how critical the error is.
ERROR_STATE()
:
- Definition: Returns the state number of the error that caused the CATCH block to execute.
- Usage: Provides additional information about the error state, which can be useful for debugging.
ERROR_LINE()
:
- Definition: Returns the line number at which the error occurred.
- Usage: Helps in pinpointing the exact location in the code where the error was raised.
ERROR_PROCEDURE()
:
- Definition: Returns the name of the stored procedure or trigger that generated the error.
- Usage: Useful for identifying the context in which the error occurred, especially in complex applications.
Example with All Error Functions
sql
1BEGIN TRY
2 -- This will cause a divide by zero error
3 SELECT 1 / 0;
4END TRY
5BEGIN CATCH
6 SELECT
7 ERROR_NUMBER() AS ErrorNumber, -- Returns the error number
8 ERROR_MESSAGE() AS ErrorMessage, -- Returns the error message
9 ERROR_SEVERITY() AS ErrorSeverity, -- Returns the severity level of the error
10 ERROR_STATE() AS ErrorState, -- Returns the state number of the error
11 ERROR_LINE() AS ErrorLine, -- Returns the line number where the error occurred
12 ERROR_PROCEDURE() AS ErrorProcedure; -- Returns the name of the stored procedure or trigger that generated the error
13END CATCH;
Note : These above functions return null if they are called outside the scope of the catch block. Error information can be retrieved by using these functions