New Throw Statement in SQL Server 2012

With RAISERROR developers had to use different ERROR_xxxx() system functions to get the error details to pass through the RAISERROR() statement, like:
  • ERROR_NUMBER()
  • ERROR_MESSAGE()
  • ERROR_SEVERITY()
  • ERROR_STATE()
let’s see an example:
  1. -- using RAISERROR()  
  2. DECLARE @ERR_MSG AS NVARCHAR(4000),  
  3. @ERR_SEV AS SMALLINT,  
  4. @ERR_STA AS SMALLINT BEGIN TRY  
  5. SELECT  
  6. 1 / 0 as DivideBYZero End Try BEGIN CATCH  
  7. SELECT  
  8. @ERR_MSG = ERROR_MESSAGE(),  
  9. @ERR_SEV = ERROR_SEVERITY(),  
  10. @ERR_STA = ERROR_STATE()  
  11. SET  
  12. @ERR_MSG = 'Error occurred while retrieving the data from database:' + @ERR_MSG RAISERROR (@ERR_MSG, @ERR_SEV, @ERR_STA) with NOWAIT End CATCH GO    
OutPut:
  1. (  
  2. 0 row(s) affected  
  3. ) Msg 50000,  
  4. Level 16,  
  5. State 1,  
  6. Line 15 Error occurred while retrieving the data  
  7. from  
  8. database : Divide by zero error encountered.  
With THROW
the benefit is: it is not mandatory to pass any parameter to raise an exception.
Just using the THROW; statement will get the error details and raise it, as shown below:
  1. - using THROW BEGIN TRY  
  2. SELECT  
  3. 1 / 0 as DivideBYZero END TRY BEGIN CATCH THROW;  
  4. END CATCH Go  
  1. Output : (  
  2. 0 row(s) affected  
  3. ) Msg 8134,  
  4. Level 16,  
  5. State 1,  
  6. Line 20 Divide by zero error encountered.  
As you see in the Output above, the error message thrown is the default one. But you can also add your customized message, we will see below.

THROW will show the exact line where the exception was occurred, here the line number is 2. But RAISERROR will show the line number where the RAISERROR statement was executed i.e. Line 15, but not the actual exception position.