Errors and Error Handling

There might be errors encountered when issuing SQL statements in a routine such as a procedure. In SQL Server 2005 and beyond, you can programmatically handle them using TRY and CATCH. The TRY block is where you put SQL statements you want to execute. The CATCH block is where control is transferred in case of error.
You can call different functions in the CATCH block to find out what went wrong, and where. Here is a list of those functions:
·         ERROR_NUMBER()
·         ERROR_MESSAGE()
·         ERROR_SEVERITY()
·         ERROR_LINE()
·         ERROR_PROCEDURE()
·         ERROR_STATE()
To indicate an error occurred in code, you used to call the RAISEERROR() function. You pass it the error message, severity, and state. This would not terminate the batch you are in. In SQL Server 2012 and beyond, you could instead do a THROW. You give it the error number, message, and state. Note that these values are not enclosed in parentheses for a THROW. The severity for a throw is always 16. THROW terminates the batch. The statement directly before a THROW must end in a semicolon.
There is a special version of THROW that has no parameters/values. It can only be issued in the CATCH block. It will effectively re-raise the error to the caller.