zoukankan      html  css  js  c++  java
  • 使用例外


    例外(exception)是一种pl/sql标示符,他用于处理pl/sql程序的运行错误。为了提高pl/sql程序的健壮性,开发人员必须要考虑pl/sql程序可能出现的各种错误,并编写相应的例外处理部分。如果不进行错误处理,那么在出现运行错误时,会终止pl/sql程序的运行,并显示错误信息。

    例子:


    declare
    v_ename emp.ename%type;
    begin
    select ename into v_ename from emp where empno=&no;
    dbms_output.put_line('雇员名:'||v_ename);
    end;
    /

    输入no的值:1111
    ORA-01403: 未找到任何数据


    处理预定义例外

     NO_DATA_FOUND   :该例外对应于ora-01403错误。当执行select into 未返回行,或者引用未初始化的pl/sql表元素时,会隐含的触发该例外。

    TOO_MANY_ROW     : 该例外对应于ora-01422错误。当执行select into语句时,如果返回超过一行,则会触发该例外。

    DUP_VAL_ON_INDEX:该例外对应于ora-00001错误。当唯一索引所对应的列上键入重复值时,会隐含的触发该例外。

    ZERO_DIVIDE           :该例外对应于ora-10476错误。当运行pl/sql块是,如果使用数字值除0,则会隐含的触发该例外。

    INVALID_CURSOR     :该例外对应于ora_01001错误。当试图在不合法的游标上执行操作时,会隐含的触发该例外。


    例子:

    declare 
    v_ename emp.ename%type;
    begin
    select ename into v_ename from emp where empno=&no;
    dbms_output.put_line('雇员名:'||v_ename);
    exception
    when no_data_found then
    dbms_output.put_line('该雇员不存在');
    end;
    /

    输入no的值:1234

    该雇员不存在

    处理非预定义例外

    非预定义例外用于于预定义例外无关的oracle错误。当使用预定义例外时,只能处理21个oracle错误。为了处理其他oracle错误,必须使用非预定义例外。使用非预定义例外的步骤 定义例外——关联例外和错误——引用例外

    例子:

    declare 
    e_integrity exception;
    pragma exception_init(e_integrity,-2291);
    begin
    update emp set deptno=&dno where empno=&eno;
    exception
    when e_integrity then 
    dbms_output.put_line('该部门不存在');
    end;
    /


    输入dno的值:15 

    输入eno 的值:7782

    该部门不存在

    因为dept表和emp表之间具有主外键关系,所以当修改雇员名的部门号时,部门号必须在dept表中存在。如果该部门不存在,则会隐含触发ora-02291对应的例外e_integrity,并显示合理的输出信息。


    处理自定义例外

    自定义例外是指pl/sql开发人员所定义的例外。预定义和非预定义例外都与oracle错误有关,并且当出现oracle错误时会隐含触发相应例外;而自定义例外与oracle错误没有任何关联,他是由开发人员为特定情况所定义的例外。步骤:定义例外——显式触发例外——引用例外

    例子:

    eclare
    e_integrity exception;
    pragma exception_init(e_integrity,-2291);
    e_no_employee exception;
    begin
    update emp set deptno=&dno where empno=&eno;
    if sql%notfound then
    raise e_no_employee;
    end if;
    exception
    when e_integrity then 
    dbms_output.put_line('该部门不存在');
    when e_no_employee then 
    dbms_output.put_line('该雇员不存在');
    end;
    /

    输入dno的值:10

    输入eno的值:1234

    该雇员不存在


    -------------------------------------------

    作者:赵杰迪

    -------------------------------------------

  • 相关阅读:
    HDU 1069 Monkey and Banana
    HDU 1029 Ignatius and the Princess IV
    HDU 1024 Max Sum Plus Plus
    Gym100923H Por Costel and the Match
    Codeforces 682C Alyona and the Tree
    Codeforces 449B Jzzhu and Cities
    Codeforces (ccpc-wannafly camp day2) L. Por Costel and the Semipalindromes
    Codeforces 598D (ccpc-wannafly camp day1) Igor In the Museum
    Codeforces 1167c(ccpc wannafly camp day1) News Distribution 并查集模板
    快乐数问题
  • 原文地址:https://www.cnblogs.com/zhaojiedi1992/p/oracle11g_sql_0015.html
Copyright © 2011-2022 走看看