Error handling in SQL Server

There are many ways to handle SQL server error.

  • Global Variable @@Error
  • TRY / CATCH Block

@@Error : whenever any error occurred within scope of your sql statements this variable is set to be non zero by sql server automatically.

To handle error in your block of code we just check if @@Error <>0 , means there are some error in code.

TRY / CATCH :  Try and catch block are used to handle the exceptions, code that is written in try block, if there is any exception occur it will go in catch block.  and in catch block we can manage the error.

There is big difference between @@Error catching error and Try/catch block.

NOTE: In above query if we are creating table that is already exists, SQL will never execute the PRINT statement in after @@Error, As SQL Server already terminate processing.

MANUALLY RAISING AN ERROR: 

RAISERROR(MessageId | message string |Variable , <Severity>, <State>[,<Argument>]) [With Option [.,..n]]

 

messageID : Message ID is found in sys.messages.

To check MessageID you have