Exception Types
Exception Types
In Oracle PL/SQL
Types of exceptions
• Named system exceptions
– Raised as a result of an error in PL/SQL or RDBMS
processing.
• Named programmer-defined exceptions
– Raised as a result of errors expected in the
application code.
• Unnamed system exceptions
– Raised as a result of an error in PL/SQL or RDBMS
processing, with codes, but no names.
• Unnamed programmer-defined exceptions.
– These are raised in the server by the programmer.
Named system exceptions
• Oracle can handle:
– CURSOR_ALREADY_OPENED (sqlcode = -6511)
– DUP_VAL_ON_INDEX (sqlcode = -1)
– INVALID_CURSOR (sqlcode = -1001)
– INVALID_NUMBER (sqlcode = -1722)
– LOGIN_DENIED (sqlcode = -1017)
– NO_DATA_FOUND (sqlcode = +100)
– TOO_MANY_ROWS (sqlcode = -1422)
– …etc…
• These are named in the ‘standard’ package in
pl/sql.
To handle these exceptions
explicitly:
• These exception names do not need to be declared.
• To handle them explicitly, put a clause in the exception
section:
EXCEPTION
When DUP_VAL_ON_INDEX
dbms_output.put_line(‘record already
there’);
When OTHER
dbms_output.put_line(‘error occurred’);
END;
Named Programmer-Defined
Exceptions
• Application-specific exceptions
– E.g.
• Negative balance in account
• Team cannot play against itself
• Cannot stock a negative number of items
• Programmer can trap these errors and handle
them.
• To do this:
– Name the error
– Check for the error and raise it
– Handle the error in the EXCEPTION section
PROCEDURE calc_annual_sales
Example
(company_id_in IN company.company_id%TYPE)
IS
no_sales_for_company EXCEPTION;
BEGIN
-- Code here to check the number of sales
-- a company has made. If none:
raise no_sales_for_company;
EXCEPTION
WHEN no_sales_for_company THEN
dbms_output.put_line(company_id||’ has made no sales’);
WHEN other THEN
rollback work;
END;
create or replace procedure add_corderline
(onum in builder.corderline.corderno%type,
scode in builder.corderline.stock_code%type,
qtyreq in builder.corderline.quantityrequired%type) as
invalid_quantity exception;
begin
if (qtyreq <= 0) then
raise invalid_quantity;
end if;
insert into corderline values(qtyreq, onum, scode);
exception
when dup_val_on_index then
dbms_output.put_line('primary key violation');
dbms_output.put_line(sqlcode||'--'|| sqlerrm);
Named System
Errors x x x √
Named
Application
Errors √ x √ √
Unnamed
System
errors √ √ x √
Unnamed
Application
Errors √ √ √ √