TSQL Exception Handling
By Rajib Bahar
1
Agenda • • • • • • • • •
What is exception handling? Simple C# exception mechanism The way we used to handle it… How is it done in TSQL? Demo What are ways to handle at client end? Demo Reflection Additional Information 2
What is exception handling? • Exception Handling is simply a breach of an application's predefined assumptions. It enables us to provide a reliable data/process validation mechanism in our applications. • SQL Server did not have any close counterpart for it until now.
3
Simple C# exception mechanism
4
The way we used to handle it… • @@ERROR – would give us the status result of last statement. If it wasn’t 0 then we know some deviant behavior occurred. • RaiseError method. • Outside of scope to discuss above two in detail
5
How is it done in TSQL? BEGIN TRY { sql_statement | statement_block } END TRY BEGIN CATCH { sql_statement | statement_block } END CATCH [ ; ]
6
Demo
7
What are ways to handle at client end?
8
Demo
9
Reflection As you may have noticed… • There is no concept of finally clause. • No standard mechanism for rethrowing exceptions. • No throwing (i.e. throw new Exception(…))
10
Additional Information • Resources – SQL Server Books Online • BEGIN CATCH statement
– Code Project
• http://www.codeproject.com/database/ExceptionHandli - Try and Catch Fun SQL Server
11
Questions? •?
12
Thank You! Rajib Bahar
13