---
title: "How to use try- catch statements in SQL Server?"  
description: "How to use try- catch statements in SQL Server?"  
author: "Steilla Mitchel"  
published: 2021-11-17  
updated: 2021-11-17  
canonical: https://www.mindstick.com/forum/156846/how-to-use-try-catch-statements-in-sql-server  
category: "mssql server"  
tags: ["sql server", "sql"]  
reading_time: 2 minutes  

---

# How to use try- catch statements in SQL Server?

How to use try- [catch](https://www.mindstick.com/forum/159341/how-to-use-try-and-catch-in-java-for-exception-handling-and-what-happens-when-an-exception-occurs) [statements in SQL](https://www.mindstick.com/forum/159028/delete-and-drop-statements-in-sql-server) [Server](https://www.mindstick.com/articles/43769/what-is-serverless-architecture-is-it-worth-switching-over)?

## Replies

### Reply by Ashutosh Kumar Verma

**Try-Catch Statement in [SQL](https://www.mindstick.com/articles/13115/types-of-keys-in-sql-or-oracle-database):**

Implement for error handling of T-SQL is similar as the exception handling in Visual Studio C# and Visual Studio C++ language. A group of T-SQL statement is closed in try block in which error or exception can arises. And if any exception is generate in try block then it catch and handles by Catch block.

## Syntax-

```
BEGIN TRY
{ SQL statement that cause to generate the exceptions}
END TRY
BEEIN CATCH
{SQL statement that cause to catch and handle the exceptions }
END CATCH
```

## Execute the Errors in CATCH block:

The following system function can be used to obtain information about the error or exception that cause to execute the CATCH block,

**ERROR_NUMBER():** Return the number of error or exceptions.

**ERROR_SEVERITY():** Return the error severity.

**ERROR_STATE():** Return the number of error state.

**ERROR_PROCEDURE() :** Return the name of that procedure or trigger in which error are generated.

**ERROR_LINE():** Return the line number inside the routine where the error are generate.

**ERROR_MESSAGE():** Return the complete text message about the error.

Following a stored procedure is create that generate error or exception and show that error in CATCH block,

```
CREATE PROCEDURE usp_ErrorHandle
AS
BEGIN TRY
    -- Generate divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
  SELECT
    ERROR_NUMBER() AS ErrorNumber
    ,ERROR_SEVERITY() AS ErrorSeverity
    ,ERROR_STATE() AS ErrorState
    ,ERROR_PROCEDURE() AS ErrorProcedure
    ,ERROR_LINE() AS ErrorLine
    ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
```

![How to use try- catch statements in SQL Server?](https://www.mindstick.com/mindstickforums/20bef02c-7b4f-4118-8d0b-5048d1d93254/images/8369cc8f-a720-4f60-8445-ff2c7f1561bb.png)\


---

Original Source: https://www.mindstick.com/forum/156846/how-to-use-try-catch-statements-in-sql-server

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
