How to generate an exception in the stored procedure in MySQL? For example:
CREATE PROCEDURE SALES() BEGIN STATEMENT... STATEMENT... STATEMENT... IF (PRICE >= 500) THEN /** THROWS AN EXCEPTION.... WHAT DO TO STOP THE PROCEDURE. **/ END IF; STATEMENT... STATEMENT... STATEMENT... END;
In MySQL I think there is no way to throw an exception in a stored procedure, but I can force an error by selecting from a non-existing table. For example:
IF (PRICE > 500) THEN /*throw the error here*/ SELECT * FROM price_greater_than_500_in_throw_exception; END IF;
Is there a more elegant way?
Thanks.
CREATE PROCEDURE SALES() BEGIN STATEMENT... STATEMENT... STATEMENT... IF (PRICE >= 500) THEN /** THROWS AN EXCEPTION....
Raising an Exception in a Stored Procedure To raise an exception in a stored procedure, use the following syntax: EXCEPTION name; where <name> is the name of an exception that already exists in the database.
For SQLEXCEPTION conditions, the stored program terminates at the statement that raised the condition, as if there were an EXIT handler. If the program was called by another stored program, the calling program handles the condition using the handler selection rules applied to its own handlers.
Instead of wrapping all of your code in a try catch block you basically add what's called a handler to your procedure. Typically you would want to stop executing, and in MySQL that is managed through an exit handler . Depending on the use case you may want to rollback or log the event when the handler is called.
Since MySQL 5.5 you can use SIGNAL and RESIGNAL for error handling. Prior to that there was no way to handle errors in MySQL. Only way is to run an erroneous query (for example inserting into non existing table).
Here is an example of how to throw an exception in mysql, which works on versions 5.5 and above:
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Custom error';
Details can be found here: https://dev.mysql.com/doc/refman/5.5/en/signal.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With