1 Mysql Exception Handling
1 Mysql Exception Handling
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:
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;
The following handler means that if a duplicate key error occurs, MySQL error 1062 is issued. It issues
an error message and continues execution.