SQLEXCEPTION
SQLEXCEPTION is a predefined subclass in SQL utilized to handle exceptions. It is a part of exception handling in SQL and it's typically activated when a SQL statement encounters an error during its execution process. These errors could be syntactical errors, issues with data or database integrity, or other SQL-related issues. SQLEXCEPTION enables the program to proficiently manage such situations, preventing it from crashing and providing a way to address and rectify the problem.
Example
Output
Explanation
In the example, a stored procedure named sampleProcedure
is created. Inside this procedure, an exit handler for SQLEXCEPTION
is declared. An SQL statement that will definitely result in an exception (dropping a non-existent table) is issued. When the procedure is called and the exception is raised, the exit handler is invoked and the message ‘An SQL exception has occurred.’ is displayed.
Example
Output
Explanation
In this example, an attempt is made to divide by zero which will throw a SQL exception. The TRY...CATCH
block captures this, and the ERROR_NUMBER()
and ERROR_MESSAGE()
functions are used to fetch the details of the exception. These details are then outputted, showing the error number (8134) and the error message (“Divide by zero error encountered.
Example
Output
Explanation
If an exception is encountered in the SQL, it will be caught by the exception handler and a customized message will be displayed as per the exception block. In this case, a custom exception named sample_exception
is initialized and then immediately raised. The exception block catches the exception and outputs the specified error message ‘SQLException encountered.’