Bird
Raised Fist0
MySQLquery~5 mins

Error handling in procedures in MySQL

Choose your learning style10 modes available
Introduction
Error handling in procedures helps you catch and manage problems during database operations so your program can respond properly instead of stopping unexpectedly.
When you want to handle division by zero errors in calculations inside a procedure.
When inserting data that might violate unique constraints and you want to handle the error gracefully.
When calling external procedures that might fail and you want to log the error or take alternative actions.
When you want to provide custom error messages to users instead of default database errors.
Syntax
MySQL
DECLARE handler_type HANDLER FOR condition_value statement;

-- Example:
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
  -- error handling code here
END;
handler_type can be CONTINUE, EXIT, or UNDO (UNDO is rarely used).
condition_value can be specific error codes, SQLSTATE values, or general conditions like SQLEXCEPTION.
Examples
This handler catches any SQL exception and continues execution after setting an error message.
MySQL
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
  SET @error_message = 'An error occurred';
END;
This handler catches duplicate entry errors and exits the procedure after setting a message.
MySQL
DECLARE EXIT HANDLER FOR 1062
BEGIN
  -- 1062 is duplicate entry error
  SET @error_message = 'Duplicate entry found';
END;
This handler is useful when fetching rows in a loop and no more rows are found.
MySQL
DECLARE CONTINUE HANDLER FOR NOT FOUND
BEGIN
  SET @no_more_rows = TRUE;
END;
Sample Program
This procedure tries to insert a user name into the users table. If any error happens, it shows a friendly error message instead of stopping abruptly.
MySQL
DELIMITER $$
CREATE PROCEDURE InsertUser(IN username VARCHAR(50))
BEGIN
  DECLARE EXIT HANDLER FOR SQLEXCEPTION
  BEGIN
    -- Handle any SQL error
    SELECT 'Error: Could not insert user.' AS message;
  END;

  INSERT INTO users (name) VALUES (username);
  SELECT 'User inserted successfully.' AS message;
END$$
DELIMITER ;

-- Call the procedure with a username
CALL InsertUser('Alice');
OutputSuccess
Important Notes
Always declare handlers at the start of the BEGIN...END block in your procedure.
Use EXIT handler to stop the procedure after an error, CONTINUE to keep going.
You can declare multiple handlers for different error types.
Summary
Error handlers catch problems during procedure execution to prevent crashes.
Use DECLARE HANDLER with CONTINUE or EXIT to control error flow.
Handlers help you give clear messages or take alternative actions on errors.

Practice

(1/5)
1. What is the main purpose of using DECLARE HANDLER in a MySQL stored procedure?
easy
A. To declare variables inside the procedure
B. To catch and handle errors during procedure execution
C. To create temporary tables for data processing
D. To optimize query performance automatically

Solution

  1. Step 1: Understand the role of DECLARE HANDLER

    DECLARE HANDLER is used to define actions when certain conditions or errors occur during procedure execution.
  2. Step 2: Identify the purpose in error handling

    It helps catch errors and decide whether to continue or exit, preventing crashes and allowing custom responses.
  3. Final Answer:

    To catch and handle errors during procedure execution -> Option B
  4. Quick Check:

    Error handling = DECLARE HANDLER usage [OK]
Hint: DECLARE HANDLER is for managing errors inside procedures [OK]
Common Mistakes:
  • Confusing DECLARE HANDLER with variable declaration
  • Thinking it creates tables or indexes
  • Assuming it optimizes queries automatically
2. Which of the following is the correct syntax to declare a handler for SQL exceptions that continues execution in MySQL?
easy
A. DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN ... END;
B. DECLARE HANDLER CONTINUE FOR SQLEXCEPTION;
C. DECLARE HANDLER FOR CONTINUE SQLEXCEPTION;
D. DECLARE HANDLER FOR SQLEXCEPTION CONTINUE;

Solution

  1. Step 1: Recall correct DECLARE HANDLER syntax

    The syntax is: DECLARE [CONTINUE|EXIT] HANDLER FOR condition statement;
  2. Step 2: Match syntax with options

    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN ... END; correctly uses DECLARE CONTINUE HANDLER FOR SQLEXCEPTION followed by a statement block.
  3. Final Answer:

    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN ... END; -> Option A
  4. Quick Check:

    Correct syntax = DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN ... END; [OK]
Hint: Syntax: DECLARE CONTINUE HANDLER FOR error BEGIN...END [OK]
Common Mistakes:
  • Placing CONTINUE after HANDLER incorrectly
  • Omitting BEGIN...END block for multiple statements
  • Wrong order of keywords
3. Consider this procedure snippet:
DECLARE EXIT HANDLER FOR SQLEXCEPTION SET @error_flag = 1;
SET @error_flag = 0;
INSERT INTO users(id, name) VALUES(1, 'Alice');
INSERT INTO users(id, name) VALUES(1, 'Bob');

Assuming id is a primary key, what will be the value of @error_flag after execution?
medium
A. 1
B. 0
C. NULL
D. Procedure will crash without setting @error_flag

Solution

  1. Step 1: Analyze the inserts and handler

    The first insert succeeds. The second insert violates primary key (duplicate id), causing an SQLEXCEPTION.
  2. Step 2: Understand EXIT HANDLER effect

    The EXIT HANDLER sets @error_flag = 1 and stops further execution.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Duplicate key error triggers EXIT HANDLER = 1 [OK]
Hint: EXIT HANDLER sets flag on error and stops execution [OK]
Common Mistakes:
  • Assuming @error_flag stays 0 despite error
  • Thinking procedure continues after EXIT HANDLER
  • Confusing CONTINUE and EXIT handlers
4. Identify the error in this MySQL procedure snippet:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE done BOOLEAN DEFAULT FALSE;
WHILE done = FALSE DO
-- some code
END WHILE;
medium
A. NOT FOUND is not a valid condition for handler
B. Missing semicolon after DECLARE statements
C. WHILE loop condition syntax is incorrect
D. Handler declared before variable 'done' is declared

Solution

  1. Step 1: Check declaration order rules

    In MySQL procedures, variables must be declared before handlers.
  2. Step 2: Identify declaration order in snippet

    The handler is declared before the variable 'done', which is invalid.
  3. Final Answer:

    Handler declared before variable 'done' is declared -> Option D
  4. Quick Check:

    Variables before handlers = correct order [OK]
Hint: Declare variables before handlers in procedures [OK]
Common Mistakes:
  • Declaring handlers before variables
  • Confusing NOT FOUND condition usage
  • Ignoring declaration order rules
5. You want to write a procedure that tries to insert a new user but if a duplicate key error occurs, it should update the user's name instead. Which error handling approach is best?
hard
A. Use DECLARE CONTINUE HANDLER for NOT FOUND to insert new user
B. Use DECLARE EXIT HANDLER for any error to rollback transaction
C. Use DECLARE CONTINUE HANDLER for duplicate key error to run UPDATE statement
D. Use no handler and rely on client application to handle errors

Solution

  1. Step 1: Understand the goal

    Insert user; if duplicate key error occurs, update existing user's name instead.
  2. Step 2: Choose handler type

    CONTINUE HANDLER allows procedure to continue after catching duplicate key error and run UPDATE.
  3. Step 3: Evaluate other options

    EXIT HANDLER stops execution, NOT FOUND is unrelated, and no handler defers error handling outside procedure.
  4. Final Answer:

    Use DECLARE CONTINUE HANDLER for duplicate key error to run UPDATE statement -> Option C
  5. Quick Check:

    CONTINUE HANDLER for duplicate key = update fallback [OK]
Hint: Use CONTINUE HANDLER to catch duplicate key and update [OK]
Common Mistakes:
  • Using EXIT HANDLER which stops procedure
  • Using NOT FOUND for duplicate key errors
  • Ignoring error handling inside procedure
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard