How can we write MySQL handler in a stored procedure?


Whenever an exception occurred in MySQL stored procedure, it is very important to handle it by throwing a proper error message. Suppose, if we do not handle the exception, there would be a chance to fail application with that certain exception in a stored procedure. MySQL provides a handler to handle the exception in the stored procedure. Followings are the four kinds of MySQL handlers which can be used in a stored procedure −

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SELECT 'got an error';

The above handler will throw an error message and continues the execution.

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET got_error=1;

The above handler will set the variable got_error to 1 and continues the execution.

DECLARE EXIT HANDLER FOR SQLEXCEPTION SET got_error=1;

The above handler will set the variable got_error to 1 and terminates the execution.

DECLARE EXIT HANDLER FOR SQLSTATE '23000' SET got_error=1;

The above handler will throw a default MySQL error message and terminates the execution by setting the variable got_error to 1.

Updated on: 22-Jun-2020

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements