Oracle数据库过程-异常处理

目录

 

目录

1.正确使用异常的好处

2.异常处理

2.1.自定义异常

2.2.预定义异常处理

2.3.使用预定义的异常


1.正确使用异常的好处

在程序发生错误时,能够准确的定位哪里产生的错误以及错误产生的原因。

2.异常处理

2.1.自定义异常

  1. 首先需要声明异常。参考:e_bade_value  EXCEPTION;
  2. 在执行过程中,需要对其进行判断,然后去抛出异常信息。参考:RAISE e_bade_value;

在执行RAISE e_bade_value; 行后,会自动跳到Exception执行语句中,在Exception中进行异常的捕获及异常的处理。
 

-- Created on 2019/4/19 by ADMINISTRATOR 
declare 
 v_companycode          ggcompany.companycode%type;
 v_new_companycode      ggcompany.companycode%type;
 e_bade_value           EXCEPTION;
begin
  v_new_companycode := '1573400000';
  select gg.companycode into v_companycode from ggcompany gg where gg.companycode = '1573400000';
  if v_new_companycode = v_companycode Then
    RAISE e_bade_value;
  end if;
Exception 
    when e_bade_value
      then 
        Dbms_Output.put_line('自定义异常成功');
    when Others
      then 
        Dbms_Output.put_line('公共异常');
end;

2.2.预定义异常处理

  在预定义异常处理中有另外一种写法,写法的参考为RASIE_APPLICATION_ERROR。
 

语法: RASIE_APPLICATION_ERROR(error_number, error_message, [keep_errors]);

error_number :范围在-20000到-20999之间的负数
error_message:是最大长度为2048字节的字符串
keep_error :是一个可选的布尔值,当值为True,新的错误将被添加到已经抛出的错误列表中,默认值为False,将新的错误代替当前的错误列表。

 注:RASIE_APPLICATION_ERROR只能在存储的子程序中调用,当被调用时,将结束当前的子程序并返回一个用户自定义的错误代码和错误消息给应用程序,这些错误代码和错误消息可以被任何Oracle错误一样被捕捉。

-- Created on 2019/4/19 by ADMINISTRATOR 
declare 
 v_companycode          ggcompany.companycode%type;
 v_new_companycode      ggcompany.companycode%type;
 e_bade_value           EXCEPTION;
begin
  --v_new_companycode := null;
  if v_new_companycode is null Then
        raise_application_error(-20000, '员工编号不能为空'); --触发应用程序异常
  ELSE
   select gg.companycode into v_companycode from ggcompany gg where gg.companycode = '1573400000';
   if v_new_companycode = v_companycode Then
    RAISE e_bade_value;
   end if;
  End if;
Exception 
    when e_bade_value
      then 
        Dbms_Output.put_line('自定义异常成功');
    when Others
      then 
        Dbms_Output.put_line(sqlerrm);
end;

2.3.使用预定义的异常

预定义的异常信息
错误号 异常错误信息名称 说明
ORA-0001 Dup_val_on_index 违反了唯一性限制
ORA-0051 Timeout-on-resource 在等待资源时发生超时
ORA-0061 Transaction-backed-out 由于发生死锁事务被撤消
ORA-1001 Invalid-CURSOR 试图使用一个无效的游标
ORA-1012 Not-logged-on 没有连接到ORACLE
ORA-1017 Login-denied 无效的用户名/口令
ORA-1403 No_data_found SELECT INTO没有找到数据
ORA-1422 Too_many_rows SELECT INTO 返回多行
ORA-1722 Invalid-NUMBER 转换一个数字失败
ORA-6500 Storage-error 内存不够引发的内部错误
ORA-6501 Program-error 内部错误
ORA-6502 Value-error 转换或截断错误
ORA-6504 Rowtype-mismatch 宿主游标变量与 PL/SQL变量有不兼容行类型
ORA-6511 CURSOR-already-OPEN 试图打开一个已处于打开状态的游标
ORA-6530 Access-INTO-null 试图为null 对象的属性赋值
ORA-6531 Collection-is-null 试图将Exists 以外的集合( collection)方法应用于一个null pl/sql 表上或varray上
ORA-6532 Subscript-outside-limit 对嵌套或varray索引得引用超出声明范围以外
ORA-6533 Subscript-beyond-count 对嵌套或varray 索引得引用大于集合中元

猜你喜欢

转载自blog.csdn.net/baidu_31572291/article/details/101377538