oracle学习笔记(第十二章:oracle例外(异常))

本文深入探讨了Oracle数据库中的异常处理机制,包括预定义异常、非预定义异常及用户自定义异常。介绍了如何定义和引发异常,并通过实例展示了不同类型的异常处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--Oracle中的例外(异常)
--预先定义的例外
--此类例外状况无须在程序中定义 , oracle会自动引发
--常见的五种标准例外 :
---no_data_found
---too_many_rows
---dup_val_on_index
---value_error
---invalid_number

declare
var1 number(4,2);
begin
var1:='yyyy';
Exception
When value_error then
Dbms_output.put_line('value error');
When others then
Dbms_output.put_line(SQLCODE||' '||SQLERRM);
End;

----非预先定义的例外﹐此类例外需在程序中定义﹐Oracle会自动引发
-----定义方法
--<例外情况> EXECPTION ;
-- PRAGMA EXCEPTION_INIT( <例外情况> , <错误码> ) ;
---例子
declare
def_exception_test Exception;
Pragma Exception_init(def_exception_test,-6502);
var1 number(4,2);
begin
var1:=24;
Exception
When def_exception_test then
dbms_output.put_line(SQLCODE||'-------'||SQLERRM);
When others then
dbms_output.put_line('other error!');
end;

--用户自定义例外
--使用者自定例外处理 , 包含.自定的例外编号 , 例外状况 , 错误讯息
--须要自行定义和自行引发
--使用者自定例外有二种使用方式 :.
--1.于 declare 中宣告,并用 RAISE 执行
--2.可用人工方式启动预先定义的例外状况处理
--利用raise
declare
test_raise Exception;
var1 varchar2(10);
begin
select emp_nm into var1 from empm where emp_no='001';
if var1<>'xxxx' then
raise test_raise;
end if;
Exception
when test_raise then
dbms_output.put_line('姓名有误﹗');
end;
--raise_application_error
--利用 Raise_application_error 程序,可产生自设的错误代码与讯息内容
--用户可定义的代码范围是﹕-20000到-20999
--例1
create or replace procedure def_err(err_no in varchar2)
as
begin
if err_no='-2000' then
raise_application_error('-20000','error!');
elsif err_no='-20500' then
raise_application_error('-20500','error2!');
end if;
end;
--例2
declare
raise_exception_test Exception;
vemp_age emp_m.emp_age%type;
begin
for empm_rec in (select emp_nm, ge from empm) loop
if empm_rec. age>=24 then
raise raise_exception_test;
end if;
end loop;
Exception
when raise_exception_test then
raise_application_error(-20000,'the age is over 24');
end ;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值