Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TRY CATCH Block in T-SQL

I encountered a stored procedure that had the following error handling block immediately after an update attempt. The following were the last lines of the SP.

Is there any benefit of doing this? It appears to me as though this code is just rethrowing the same error that it caught without any value added and that the code would presumably behave 100% the same if the Try Block were ommited entirely.

Would there be ANY difference in the behavior of the resulting SP if the TRY block were ommitted?

BEGIN CATCH

SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSev = ERROR_SEVERITY(), @ErrState = ERROR_STATE()
        RAISERROR (@ErrMsg, @ErrSev, @ErrState)

END CATCH
like image 521
Chad Avatar asked Feb 14 '11 14:02

Chad


2 Answers

Barring the fact that the "line error occured on" part of any message returned would reference the RAISERROR line and not the line the error actually occured on, there will be no difference. The main reason to do this is as @Chris says, to allow you to programmatically use/manipulate the error data.

like image 110
Philip Kelley Avatar answered Sep 24 '22 20:09

Philip Kelley


What we usually do in our stored procedure is to write the catch block like this

BEGIN CATCH
  DECLARE @i_intErrorNo int          
  DECLARE @i_strErrorMsg nvarchar(1000)          
  DECLARE @i_strErrorProc nvarchar(1000)          
  DECLARE @i_intErrorLine int          

  SELECT @i_intErrorNo=Error_Number()          
  SELECT @i_strErrorMsg=Error_Message()          
  SELECT @i_strErrorProc=Error_Procedure()          
  SELECT @i_intErrorLine=Error_Line()   

  INSERT INTO error table ////// Insert statement. 

END CATCH 

This is something we use to do to store error. For proper message to user, I always use the output parameter to the stored procedure to show the detailed/required reason of the error.

like image 36
Chris Avatar answered Sep 23 '22 20:09

Chris