Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
What's New in SQL Server 2012

You're reading from  What's New in SQL Server 2012

Product type Book
Published in Oct 2012
Publisher Packt
ISBN-13 9781849687348
Pages 238 pages
Edition 1st Edition
Languages

Table of Contents (19) Chapters

What's New in SQL Server 2012
Credits
About the Authors
Acknowledgment
Acknowledgment
About the Reviewers
www.PacktPub.com
Preface
Installing SQL Server 2012 SQL Server Administration Transact SQL Analysis Services Reporting Services Integration Services Data Quality Services AlwaysOn Distributed Replay Big Data and the Cloud Index

Error handling with THROW


The TRY... CATCH error handling construct is very similar in T-SQL to exception handling in languages such as C# or VB.NET. In T-SQL it consists of a TRY block and a CATCH block, which must always be paired. If an error occurs in the TRY block, it is passed to the CATCH block code to handle.

In previous versions of SQL Server you would use @@RAISE_ERROR and would need to neatly collect the error data and return this. Let us look at an example that will throw n error:

BEGIN TRY  
  DECLARE @MyInt int
  SET @MyInt = 1 / 0  
END TRY   
BEGIN CATCH  
  DECLARE @ErrorMessage nvarchar(4000), @ErrorSeverity int
  SELECT @ErrorMessage = ERROR_MESSAGE(), 
  @ErrorSeverity = ERROR_SEVERITY()  
  RAISERROR (@ErrorMessage, @ErrorSeverity, 1)  
END CATCH

This is the result:

In the preceding CATCH block, there is a lot of work going on to collect the details of this error. Now there is a slicker way of finding out what has caused the error. Compare the above code to the code below...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}