PLSQL基础语法三-异常

--异常处理
--练习1:捕获no_data_found异常
declare
 r_student student%rowtype;
begin
  select id,name,email,age into r_student from student where id=5;
  dbms_output.put_line('name:'||r_student.name);
  exception
    when no_data_found then
      dbms_output.put_line('数据没有找到');
      when others then
        dbms_output.put_line('其他异常');
  end;
--实际开发中,我们常常创建一个错误表来处理收集异常信息,通过sqlcode,sqlerrm这两个函数来收集信息  
--sqlcode:返回错误代码
--sqlerrm:返回与错误代码关联的消息
/*
create table tb_error(
       id number primary key,
       tablename varchar2(10),
       sqlcode varchar2(50),
       sqlerrm varchar2(200),
       createdate date default sysdate
);
create sequence seq_tb_error;
*/
--练习2:处理异常
declare
 r_student student%rowtype;
 v_sqlcode varchar2(50);
 v_sqlerrm varchar2(200);
begin
  select id,name,email,age into r_student from student where id=5;
  dbms_output.put_line('name:'||r_student.name);
  exception
     when others then
      v_sqlcode:=SQLCODE;
      v_sqlerrm:=SQLERRM;
      insert into tb_error values(seq_tb_error.nextval,'student',v_sqlcode,v_sqlerrm,default);
      commit;
  end;
--练习3:自定义异常
DECLARE  
   v_empno employees.employee_id%TYPE :=&empno;  
   no_result  EXCEPTION;              --1、定义  
BEGIN  
   UPDATE employees SET salary = salary+100 WHERE employee_id = v_empno;  
   IF SQL%NOTFOUND THEN  
      RAISE no_result;                --2、抛出  
   END IF;  
EXCEPTION  
   WHEN no_result THEN                --3、处理  
      DBMS_OUTPUT.PUT_LINE('你的数据更新语句失败了!');  
   WHEN OTHERS THEN  
      DBMS_OUTPUT.PUT_LINE(SQLCODE||'---'||SQLERRM);  
END;



你可能感兴趣的:(oracle,plsql)