Oracle笔记之异常


异常:提高程序的健壮性

DECLARE
  

BEGIN
  --触发异常

EXCEPTION
 --处理异常

END;

如果不处理异常,会将异常传递到应用环境

create or replace procedure get_name as
       v_name emp.ename%TYPE;
begin
       select ename into v_name from emp;
       dbms_output.put_line('name: ' || v_name);
end;

在这里插入图片描述

(一)处理系统异常情况

create or replace procedure get_name as
       v_name emp.ename%TYPE;
begin
       select ename into v_name from emp;
       dbms_output.put_line('name: ' || v_name);
exception
       when TOO_MANY_ROWS then --还有很其它预定义的异常:NO_DATA_FOUND
         dbms_output.put_line('返回了太多的数据行');
       when others then
         null;      
end;

在这里插入图片描述

(二)处理非预定义异常(有代码,但没有标识)

create table t(id int check(id >10),name varchar(30));

create or replace procedure insert_data_to_t as
begin
  insert into t values(2,'chen'); -- -2290
end;

在这里插入图片描述

create or replace procedure insert_data_to_t as
   check_id_exception exception;
   PRAGMA EXCEPTION_INIT(check_id_exception,-2290);
begin
  insert into t values(2,'chen');
exception
  when check_id_exception then
    dbms_output.put_line('id 号必须大于10');
  when others then
    null;
end;

在这里插入图片描述

(三)自定义异常(预定义异常和非预定义异常都与oracle有关,并且发生错误时隐含的触发,而自定义则与oracle没有关系,它必须要显式的触发)

create or replace procedure update_data_t as
begin
   update t set name='chen' where id = 1000;--其实没有这个人,但是没有任何的提示
end; 

在这里插入图片描述

create or replace procedure update_data_t as
   no_student_exception exception;
begin
   update t set name='chen' where id = 1000;
   if SQL%NOTFOUND then
     raise no_student_exception;
   end if;
exception
  when no_student_exception then
     dbms_output.put_line('没有数据被更新');
  when others then
     null;
end;

在这里插入图片描述

posted on 2021-11-29 19:34  JAVA开发区  阅读(19)  评论(0)    收藏  举报  来源