(Oracle)异常处理的相关知识与实例

来源:互联网 发布:5230手机加密软件 编辑:程序博客网 时间:2024/06/08 12:07

异常

还是用实例和注释来诠释吧!

实例1

查询empno=1234的雇员名字(emp表中无此雇员)

set serveroutput on

declare

  v_ename emp.ename%type;

begin

  select ename into v_ename from emp whereempno=1234;

  dbms_output.put_line(v_ename);

exception                    --异常处理的标识,它位于begin之后

  when no_data_found  then  --判断异常

    dbms_output.put_line('雇员编号错误,没有找到相应雇员!');   --显示异常信息

  when others then

    dbms_output.put_line('未知错误!');

end;

实例2

自定义异常

set serveroutput on

declare

  insert_error exception;    --自定义异常insert_error

  pragma exception_init(insert_error,-1400);  --将自定义的异常insert_error与系统异常1400相关联

begin

  insert into emp(empno) values(null);      --注:emp表中empno为主键,空值是不允许的,所以会异常

exception          --异常标识

  when insert_error then   --判断异常

    dbms_output.put_line('不能插入空值!');

  when others then

    dbms_output.put_line('未知异常!');

end;

实例3

真正的自定义异常

set serveroutput on

declare

  new_excep exception;   --自定义异常new_excep

  p_deptno emp.deptno%type;

  cursor emp_cursor is select ename from emp where deptno=p_deptno;

  v_ename emp.ename%type;

begin

  p_deptno:=40;            --通过改变它的值来实现程序的效果

  open emp_cursor;

  if p_deptno in(10,20,30)  then

    dbms_output.put_line('部门'||p_deptno||'的雇员:');

    loop

      fetch emp_cursor into v_ename;

      exit when emp_cursor%notfound;

      dbms_output.put_line(v_ename);

    end loop;

  else

    raise new_excep;         --触发异常new_excep

  end if;

exception

  when new_excep  then       --判断异常

    dbms_output.put_line('部门不存在!');

  when others then

    dbms_output.put_line('未知异常!');

end;

实例4

使用raise_application_error 函数引发系统异常

set serveroutput on

declare

  v_empno emp.empno%type;

begin

  v_empno:=8888;

  insert into emp(empno,ename)values(v_empno,'JACK');

  if v_empno<7000 then

    rollback;

    raise_application_error(-20001,'编号小于7000');    --用函数引发系统异常

  end if;

  if v_empno>8000 then

    rollback;

    raise_application_error(-20001,'编号大于8000');

  end if;

end;

原创粉丝点击