Skip to content

Commit 0aa0462

Browse files
authored
Merge pull request #13 from rahull0328/dev
added new answer
2 parents 3a417ee + 17eb384 commit 0aa0462

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

README.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1701,6 +1701,84 @@ END;
17011701

17021702
#### Q. How can you raise custom errors from stored procedure?
17031703

1704+
**✅ Raising Custom Errors from a Stored Procedure in SQL Server**
1705+
1706+
In SQL Server, you can raise custom errors from a stored procedure using the RAISERROR statement (for older versions) or THROW (introduced in SQL Server 2012 and preferred for modern code).
1707+
1708+
**🔹 1. Using RAISERROR**
1709+
1710+
```sql
1711+
RAISERROR (message_string, severity, state);
1712+
```
1713+
1714+
- message_string: Custom error message (max 4000 chars).
1715+
1716+
- severity: Number from 0 to 25 (>=11 generates an error).
1717+
1718+
- state: Any integer from 0 to 255 (used to identify the location in code).
1719+
1720+
**💡 Example:**
1721+
1722+
```sql
1723+
CREATE PROCEDURE CheckAge
1724+
@Age INT
1725+
AS
1726+
BEGIN
1727+
IF @Age < 18
1728+
BEGIN
1729+
RAISERROR('Age must be 18 or above.', 16, 1);
1730+
RETURN;
1731+
END
1732+
1733+
PRINT 'Access granted.';
1734+
END;
1735+
```
1736+
1737+
**🔹 2. Using THROW (SQL Server 2012+)**
1738+
1739+
```sql
1740+
THROW [error_number, message, state];
1741+
```
1742+
1743+
**💡 Example:**
1744+
1745+
```sql
1746+
CREATE PROCEDURE CheckBalance
1747+
@Balance INT
1748+
AS
1749+
BEGIN
1750+
IF @Balance < 0
1751+
BEGIN
1752+
THROW 50001, 'Balance cannot be negative.', 1;
1753+
END
1754+
1755+
PRINT 'Balance is valid.';
1756+
END;
1757+
```
1758+
- 50001: Custom error number (must be >= 50000 for user-defined errors).
1759+
1760+
- THROW automatically includes error severity (16) and can be caught in TRY...CATCH.
1761+
1762+
**🔹 3. Using TRY...CATCH with THROW**
1763+
1764+
```sql
1765+
BEGIN TRY
1766+
-- Some risky operation
1767+
IF NOT EXISTS (SELECT * FROM Users WHERE UserId = 1)
1768+
THROW 50002, 'User not found.', 1;
1769+
END TRY
1770+
BEGIN CATCH
1771+
PRINT 'Error occurred:';
1772+
PRINT ERROR_MESSAGE(); -- Retrieves the thrown error
1773+
END CATCH
1774+
```
1775+
1776+
**🧠 When to Use:**
1777+
1778+
- Use RAISERROR for backward compatibility.
1779+
1780+
- Use THROW for cleaner, modern syntax and when re-throwing caught exceptions.
1781+
17041782
<div align="right">
17051783
<b><a href="#table-of-contents">↥ back to top</a></b>
17061784
</div>

0 commit comments

Comments
 (0)