ITPub博客

首页 > 数据库 > Oracle > Oracle中的异常处理

Oracle中的异常处理

原创 Oracle 作者:ITtomilk 时间:2015-11-10 13:56:13 0 删除 编辑
异常处理是Oracle中必不可少的部分。


点击(此处)折叠或打开

  1. begin
  2. exception
  3. end;


我们常见的异常no_data_found


点击(此处)折叠或打开

  1. declare
  2. inumber;
  3. begin
  4. select1 onto ifromdualwhere1=2;
  5. exception
  6. when not_data_found
  7. then
  8. dbms.output.put_line('not found data')
  9. end;


还有when too_many_rows


点击(此处)折叠或打开

  1. declare
  2. nnumber;
  3. begin
  4. selectidinton
  5. from
  6. (
  7. select1 idfromdual
  8. union
  9. select2 idfromdual
  10. );
  11. exception when too_many_rowsthen
  12. dbms_output.put_line('too many rows found for n');
  13. end;


还有很多我们无法确认的异常处理,这种情况我们可以使用others代替其他所有的异常。


点击(此处)折叠或打开

  1. EXCEPTION
  2. when others then
  3. rollback;
  4. dbms_output.put_line('code:'||sqlcode);
  5. dbms_output.put_line('errm:'||sqlerrm);
  6. raise;


when others then和raise;异常分很多种类,如NO_FOUND。others处本应该写异常名称,如果不想把异常分得那麼细,可以笼统一点用others来捕获,即所有异常均用others来捕获。when others then表示是其它异常。 raise表示抛出异常。我们还可以自己定义exception哦!为什么要自己定义呢?即使人为制造exception,中断程序或者跳出某个程序段。


点击(此处)折叠或打开

  1. DECLARE
  2. exception1 EXCEPTION;
  3. BEGIN
  4.     IF1!=1THEN
  5.     Dbms_Output.put_line('Normal!');
  6.     ELSE
  7.     RAISE exception1;
  8.     ENDIF;
  9. EXCEPTION
  10. WHEN exception1THEN
  11. Dbms_Output.put_line('EXCEPTION!');
  12. WHEN OTHERSTHEN
  13. Dbms_Output.put_line('OTHERS EXCEPTION!');
  14. END;


输出结果是:EXCEPTION!

因为我人为raise了一个exception,所以程序直接跳到了when exception1 then里面去了。 注意:exception一定有一个begin和end。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30260000/viewspace-1826913/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2015-05-25

  • 博文量
    42
  • 访问量
    90724