How can Oracle throw a custom exception?
In Oracle, you can throw custom exceptions using the `RAISE` statement. The first step is to define an exception in the database.
CREATE OR REPLACE EXCEPTION custom_exception_name[PRAGMA EXCEPTION_INIT (exception_name, -error_code)];
In this case, `custom_exception_name` is the name of a custom exception that can be named as needed. You can choose to initialize the exception using `PRAGMA EXCEPTION_INIT`, specifying the error code (`error_code`). When it is necessary to raise an exception, use the `RAISE` statement.
RAISE custom_exception_name;
Alternatively, you can specify an exception message when throwing an exception.
RAISE_APPLICATION_ERROR(error_code, 'error_message');
“Among them, `error_code` represents the code for the error, and `error_message` represents the error message. Here is a complete example: creating an exception.”
CREATE OR REPLACE EXCEPTION custom_exceptionPRAGMA EXCEPTION_INIT (custom_exception, -20001);
Create a stored procedure
CREATE OR REPLACE PROCEDURE custom_exception_exampleIS
BEGIN
-- 抛出异常
RAISE custom_exception;
EXCEPTION
WHEN custom_exception THEN
-- 处理异常
DBMS_OUTPUT.PUT_LINE('Custom Exception Raised');
END;
In the example above, when the `custom_exception_example` stored procedure is called, it will throw a custom exception `custom_exception`, which will then be handled by the exception handling section.