Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 try/catch

Author  Topic 

Robowski
Posting Yak Master

101 Posts

Posted - 2013-11-14 : 06:26:02
Just started using try/catch and hit a problem.

Tried simplifying it and would expect the below to print '1 = 1' but it isn't.

BEGIN TRY
BEGIN TRAN
PRINT '1 = 2'
COMMIT TRAN
END TRY
BEGIN CATCH
IF 1 = 1
BEGIN
PRINT '1 = 1'
END;
IF 1 = 1 ROLLBACK TRAN
THROW;
END CATCH

vijays3
Constraint Violating Yak Guru

354 Posts

Posted - 2013-11-14 : 06:32:48
There is no error in Try block so it wont move into catch block
everything is fine in try block so it is printing 1 = 2




BEGIN TRY
BEGIN TRAN
--PRINT '1 = 2'
select 1/0
COMMIT TRAN
END TRY
BEGIN CATCH
IF 1 = 1
BEGIN
PRINT '1 = 1'
END;

--IF 1 = 1 ROLLBACK TRAN
--THROW;
END CATCH

Vijay is here to learn something from you guys.
Go to Top of Page

Robowski
Posting Yak Master

101 Posts

Posted - 2013-11-14 : 06:38:02
I see, so you can't use the begin catch block to create custom errors?

For example, if more than two rows are inserted throw and error?

Would have to revert to a using raiserror within a transaction instead?


quote:
Originally posted by vijays3

There is no error in Try block so it wont move into catch block
everything is fine in try block so it is printing 1 = 2




BEGIN TRY
BEGIN TRAN
--PRINT '1 = 2'
select 1/0
COMMIT TRAN
END TRY
BEGIN CATCH
IF 1 = 1
BEGIN
PRINT '1 = 1'
END;

--IF 1 = 1 ROLLBACK TRAN
--THROW;
END CATCH

Vijay is here to learn something from you guys.

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-11-14 : 07:32:25
quote:
Originally posted by Robowski

I see, so you can't use the begin catch block to create custom errors?

For example, if more than two rows are inserted throw and error?

Would have to revert to a using raiserror within a transaction instead?


quote:
Originally posted by vijays3

There is no error in Try block so it wont move into catch block
everything is fine in try block so it is printing 1 = 2




BEGIN TRY
BEGIN TRAN
--PRINT '1 = 2'
select 1/0
COMMIT TRAN
END TRY
BEGIN CATCH
IF 1 = 1
BEGIN
PRINT '1 = 1'
END;

--IF 1 = 1 ROLLBACK TRAN
--THROW;
END CATCH

Vijay is here to learn something from you guys.




yep. you need to use RAISERROR for that. Or if in SQL 2012 or later use THROW

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -