0% found this document useful (0 votes)
48 views

1 Mysql Exception Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

1 Mysql Exception Handling

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

MySQL Error Handling in Stored Procedures

When an error occurs inside a stored procedure, it is important to handle it appropriately, such as
continuing or exiting the current code block’s execution, and issuing a meaningful error message.
MySQL provides an easy way to define handlers that handle from general conditions such as warnings
or exceptions to specific conditions e.g., specific error codes.

Declaring a handler
To declare a handler, you use the DECLARE HANDLER statement as follows:

DECLARE action HANDLER FOR condition_value statement;

If a condition whose value matches the condition_value , MySQL will execute the statement and
continue or exit the current code block based on the action .
The action accepts one of the following values:
 CONTINUE : the execution of the enclosing code block ( BEGIN … END ) continues.
 EXIT : the execution of the enclosing code block, where the handler is declared, terminates.
The condition_value specifies a particular condition or a class of conditions that activates the
handler. The condition_value accepts one of the following values:
 A MySQL error code.
 A standard SQLSTATE value. Or it can be an SQLWARNING , NOTFOUND or SQLEXCEPTION
condition, which is shorthand for the class of SQLSTATE values. The NOTFOUND condition is used
for a cursor or SELECT INTO variable_list statement.
 A named condition associated with either a MySQL error code or SQLSTATE value.
The statement could be a simple statement or a compound statement enclosing by the BEGIN and END
keywords.

The following handler means that if an error occurs, set the value of the has_error variable to 1 and
continue the execution.
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET has_error = 1;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_row_found = 1;

The following handler means that if a duplicate key error occurs, MySQL error 1062 is issued. It issues
an error message and continues execution.

DECLARE CONTINUE HANDLER FOR 1062


SELECT 'Error, duplicate key occurred';

You might also like