数据库之【异常处理篇】

****************************

数据库之【异常处理篇】

****************************


--预定义异常详细列表
access_into_null    在未初化对象时出现
case_not_found      在CASE语句中的选项与用户输入的数据不匹配时出现
collection_is_null  在给尚未初始化的表或数组赋值时出现
cursor_already_open 在用户试图打开已经打开的游标时出现
dup_val_on_index    在用户试图将重复的值存在使用唯一索引的数据库列中时出现
invalid_cursor      在执行非法游标运算(如打开一个尚未打开的游标)时出现
invalid_number      在将字符串转换为数字时出现
login_denied        在输入的用户名或密码无效时出现
no_data_found       在表中不存在的请求的行时出现,此外,当程序引用已经删除的元素时
storage_error       在内存损坏或PL/SQL耗尽内存时出现
too_many_rows       在执行SELECT INTO语句后返回多行时出现
value_error         在产生大小限制错误时出现
zero_divide         以零作除数时出现
others              所有异常

-在PLSQL块中,如果不使用错误捕获,可以直接使用
raise_application_error(-20001,'工资太低');
--错误处理,-20001/*-20000到20999*/, '未指定项费率'/*2048字节*/,在语句执行部分使用,如果不是自定义错误的抛出,则不能与EXCEPTION一起使用

--如果要打印出所有错误信息:
dbms_output.put_LINE(SQLCODE||SQLERRM);
--SQLCODE错误编号
--SQLERRM错误信息

declare
  --预定义错误(返回多行)
  s_al number;
begin
  select sal into s_al from emp;
exception
  when too_many_rows then
    dbms_output.put_line('返回多行');
end;

declare
  --记录没找到
  s_al number;
begin
  select sal into s_al from emp where empno = 1;
exception
  when no_data_found then
    dbms_output.put_line('记录没找到');
end;

declare
  --自定义错误
  s_al number;
  err exception;
begin
  select sal into s_al from emp where empno = 7369;
  if s_al < 3000 then
    dbms_output.put_line(s_al);
    raise err;
  else
    dbms_output.put_line(s_al);
  end if;
exception
  when err then
    dbms_output.put_line('工资太低');
end;

--引发应用程序错误
declare
  s_al number;
  err exception; --定义错误
begin
  select sal into s_al from emp where empno = 7369;
  if s_al < 3000 then
    dbms_output.put_line(s_al);
    raise err; --抛出错误
  else
    dbms_output.put_line(s_al);
  end if;
exception
  --错误捕获
  when err then
    raise_application_error(-20001, '工资太低'); --错误处理,-20001/*-20000到20999*/, '未指定项费率'/*2048字节*/
end;



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章