SQL Error Handling in Procedures and Scripts
π‘ Concept Name
SQL Error Handling β A set of techniques and constructs like TRY...CATCH, RAISERROR, and transactions used to catch, handle, or log errors gracefully in SQL scripts and stored procedures.
π Quick Intro
Error handling ensures your SQL procedures remain consistent and stable during failures like divide-by-zero, constraint violations, or failed inserts. SQL Server uses TRY...CATCH blocks to detect and respond to these errors programmatically.
π§ Analogy / Short Story
Imagine assembling furniture. If a part is missing, you stop, check the manual, and either skip that step or return the product. SQL error handling is similarβit checks if an operation fails, logs or reports it, and either rolls back or exits gracefully instead of crashing mid-execution.
π§ Technical Explanation
- TRY...CATCH lets you catch runtime errors in SQL Server and handle them in the CATCH block.
- Functions like
ERROR_MESSAGE()
,ERROR_NUMBER()
, andERROR_LINE()
retrieve error details. RAISERROR
orTHROW
lets you raise custom errors with severity and state.- Transactions can be used with error handling to
ROLLBACK
if anything fails. - Other DBMSs like PostgreSQL use
BEGIN ... EXCEPTION WHEN
blocks instead.
π» Real Code Example
BEGIN TRY
BEGIN TRANSACTION
-- Intentional divide by zero
DECLARE @x INT = 1 / 0;
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
PRINT 'Error Number: ' + CAST(ERROR_NUMBER() AS VARCHAR);
PRINT 'Message: ' + ERROR_MESSAGE();
END CATCH

π― Purpose & Use Case
- β Prevent inconsistent data by rolling back failed transactions.
- β Log error details to a custom error log table.
- β Provide user-friendly messages for apps consuming stored procedures.
- β Ensure mission-critical operations fail gracefully without halting the entire system.
β Interview Q&A
Q1: How do you handle runtime errors in SQL Server?
A: Using TRY...CATCH blocks to catch exceptions and take corrective action like ROLLBACK.
Q2: What is the role of ROLLBACK in error handling?
A: It undoes all changes in the current transaction to maintain consistency.
Q3: What function returns the actual error message in SQL Server?
A: ERROR_MESSAGE()
.
Q4: Can you raise a custom error in SQL Server?
A: Yes, using RAISERROR
or THROW
.
Q5: What is a common use of error logging?
A: Inserting error info into a log table for auditing/debugging.
Q6: Can a transaction be resumed after a CATCH block?
A: No, once rolled back, a new transaction must be started.
Q7: What happens if you donβt handle errors in SQL?
A: The script halts and may leave the database in an inconsistent state.
Q8: Are error-handling features the same in all RDBMS?
A: No, syntax and functions differ across SQL Server, PostgreSQL, MySQL, etc.
Q9: Whatβs a good pattern for robust SQL scripts?
A: Combine TRY...CATCH with transactions and logging.
Q10: How can errors be logged automatically?
A: Insert error details into a dedicated error log table in the CATCH block.
π MCQs
Q1. What SQL construct catches errors?
- IF...ELSE
- BEGIN...END
- TRY...CATCH
- WHILE...BREAK
Q2. Which function returns the SQL error message?
- RAISEERROR()
- GET_ERROR()
- ERROR_MSG()
- ERROR_MESSAGE()
Q3. What does ROLLBACK do?
- Commits the transaction
- Starts a new transaction
- Undoes changes in the current transaction
- Logs the error
Q4. Which keyword raises a custom error in SQL Server?
- THROWEX
- RAISE
- THROW
- RAISERROR
Q5. Why use error logging?
- To boost performance
- To audit failures
- To improve UI
- To increase concurrency
Q6. What happens if error is not handled?
- Script continues
- Script halts and may corrupt data
- Database restarts
- Transaction pauses
Q7. What clause is used to exit a transaction on error?
- BREAK
- RETURN
- ROLLBACK
- RAISE
Q8. What should you check for before COMMIT?
- Keys
- Errors
- Duplicates
- Indexes
Q9. How to handle errors in PostgreSQL?
- TRY...CATCH
- EXCEPTION BLOCK
- BEGIN...EXCEPTION
- CATCH THROW
Q10. Can you log errors into a table?
- No
- Yes
- Only in triggers
- Only with jobs
π‘ Bonus Insight
Combine TRY...CATCH blocks with custom error logging tables and RAISERROR
levels for a production-grade error recovery strategy. Always wrap critical sections in transactions to prevent partial data persistence.
π PDF Download
Need a handy summary for your notes? Download this topic as a PDF!