Like just about every other technique in Microsoft SQL you can nest your exception handling. The basic template is:
BEGIN TRY BEGIN TRY -- Nested try block END TRY BEGIN CATCH -- Nested catch block END CATCH END TRY BEGIN CATCH --catch block END CATCH
You can do this as many levels deep as you feel necessary. I will say that it is often easier to accomplish this nesting by handing the different steps in separate stored procedures. That way you can handle errors on a more “atomic” or “unit” level.
The template I shared with you before will only handle errors raised by the database engine. If you need to detect for business logic errors, you can take the initiative, and raise your own errors.
RAISERROR ( { msg_id | msg_str | @local_variable } { ,severity ,state } [ ,argument [ ,...n ] ] ) [ WITH option [ ,...n ] ]
I’ve mentioned this before, but right now I don’t have an article dedicated to it, so I’ll go over it now. RAISERROR takes three required arguments:
The first argument can be one of three things:
- The argument can be represented as a constant integer. To start, create a message, assign it a number higher than 50000, and pass that message to Transact-SQL by storing it in the sys.messages library. If you do this, to access the message, you would use the number you specified
- The argument can be represented as a msg_str object. In this case, the argument is the message you want to produce (or display) if an error occurs. The argument is created and formatted like the printf() function of the C language
- The first argument can be a string-based locally declared variable. It is then initialized and formatted as done for the msg_str option
That’s it for nesting error handling, and raising your own errors. If you have any questions, let me know. I’m here to help!