Sql-server – Purpose of Try/Catch without Transactions

error handlingsql serversql-server-2016

I have come across the following code (SQL Server 2016, 2008-compatible database):

CREATE PROCEDURE myProc
AS BEGIN
    DECLARE @ERRORMESSAGE As VARCHAR(1000)

    BEGIN TRY   
        DELETE FROM Foo -- (statement #1)
        DELETE FROM Bar -- (statement #2)
    END TRY
    BEGIN CATCH
        SET @ERRORMESSAGE = ERROR_MESSAGE()
        RaisError(@ERRORMESSAGE,16,1) 
    END CATCH   
END

What is the purpose of the try/catch block?

For the sake of discussion, lets assume there are no triggers called and the client code that executes this procedure does not wrap the call in a transaction.

I had to fix a bug in code similar to this where statement #2 raised an error. Looking at the data it appeared statement #1 completed successfully and statement #2 did not apply (obviously).

One thing this does is not give a clear line number when trying to debug the crash, but is there anything legitimate this does?

Best Answer

IMHO Using a TRY/CATCH block you don't need to check every single operation.

DELETE FROM Foo;
IF @@ERROR <> 0
BEGIN
    RAISERROR('Error deleting table Foo', 16, 1);
    RETURN -1;
END

OR

DELETE FROM Bar;
IF @@ERROR <> 0
BEGIN
    SET @ErrMsg = 'Error';
    GOTO ERROR;
END