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(), and ERROR_LINE() retrieve error details.
  • RAISERROR or THROW 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!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: