---
title: "How exceptions can be handled in SQL Server Programs?"  
description: "How exceptions can be handled in SQL Server Programs?"  
author: "Ashutosh Patel"  
published: 2023-03-22  
updated: 2023-04-12  
canonical: https://www.mindstick.com/forum/157528/how-exceptions-can-be-handled-in-sql-server-programs  
category: "mssql server"  
tags: ["mssql server", "sql server", "sql"]  
reading_time: 1 minute  

---

# How exceptions can be handled in SQL Server Programs?

How [exceptions](https://www.mindstick.com/interview/22871/define-predifined-generic-exceptions) can be handled in [SQL Server](https://www.mindstick.com/articles/12999/what-is-table-valued-function-in-sql-server) [Programs](https://answers.mindstick.com/qa/49851/can-mac-os-x-programs-run-on-windows)?

## Replies

### Reply by Krishnapriya Rajeev

In [SQL](https://www.mindstick.com/articles/13115/types-of-keys-in-sql-or-oracle-database) [Server](https://www.mindstick.com/articles/43769/what-is-serverless-architecture-is-it-worth-switching-over), exceptions can be handled using the *TRY...CATCH* construct. This construct allows you to catch and handle errors that occur during the execution of a SQL Server program.

Here's an example of how to use TRY...CATCH to handle exceptions in a SQL Server stored procedure:

```plaintext
CREATE PROCEDURE my_proc
AS
BEGIN
  BEGIN TRY
    -- SQL Server code that might cause an exception
  END TRY
  BEGIN CATCH
    -- Handle the exception here
    PRINT 'An error occurred: ' + ERROR_MESSAGE()
  END CATCH
END
```

In this example, the SQL Server code that might cause an exception is placed inside the TRY block. If an error occurs while executing the code in the TRY block, the exception is caught by the CATCH block.

The ERROR_MESSAGE() function is used to retrieve the error message associated with the exception. You can also use other functions like *ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(),* and *ERROR_PROCEDURE()* to get more information about the error.

You can also use the RAISERROR statement to raise a *custom error message* and specify the severity level of the error.


---

Original Source: https://www.mindstick.com/forum/157528/how-exceptions-can-be-handled-in-sql-server-programs

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
