TRY and CATCH is a very helpful way to identify errors on basically any major programming language, and MSSQL is not the exception.
Using TRY and CATCH will let us check if the query we want to execute will fail, and if so do something about it, here is a basic example:
For this we will use AdventureWorks Microsoft database sample.
BEGIN TRY INSERT INTO PERSON.Person (BusinessEntityID,PersonType,FirstName,LastName) VALUES ('X','EM','Hiram','Romero') END TRY BEGIN CATCH SELECT ERROR_MESSAGE() as Error END CATCH
The above example returns:
“Conversion failed when converting the varchar value ‘X’ to data type int.”
Because the column BusinessEntityID is an int value, and we tried to insert a varchar (letter X).
NOTE! This example doesn’t interrupts the QUERY execution.