For a start catching everything using EXCEPTION WHEN OTHERS
is not necessarily the best practice. If you handle an exception you should know exactly what you're going to do with it. It's unlikely that you have the ability to handle every single Oracle exception properly using OTHERS and if you do so you should probably be logging them somewhere where they'll be noticed.
To quote from Oracle's Guidelines for Avoiding and Handling Exceptions:
Whenever possible, write exception handlers for named exceptions instead of using OTHERS exception handlers.
Learn the names and causes of the predefined exceptions. If you know that your database operations might raise specific internally defined exceptions that do not have names, then give them names so that you can write exception handlers specifically for them.
To answer your question you can use the raise_application_error
procedure to raise an error at any point in your code:
RAISE_APPLICATION_ERROR (-20000, 'an exception');
The user defined exceptions are those between 20,000 and 20,999 so ensure you use a number in this range.
An example could be:
begin
raise_application_error(-20500, 'an exception occurred');
exception when others then
do_something;
end;
/
You can also define your own pre-defined exception, which you can then catch:
declare
my_exception EXCEPTION;
PRAGMA EXCEPTION_INIT( my_exception, -20001 );
begin
raise_application_error( -20001, 'an exception' );
exception when my_exception then
do_something;
end;