PL / SQL异常

时间:2018-02-06 06:04:32

标签: plsql oracle11g plsqldeveloper

有没有办法将此错误(ORA-06502:PL / SQL:数字或值错误:字符到数字转换错误)捕获到异常中?每当我使用string作为输入时就会发生这种情我想当其他人例外会抓住它但它不会。

DECLARE
    v_order_no NUMBER(10) := &Order_Number;
    var NUMBER(10);
BEGIN
    SELECT 1 INTO var
    FROM tbl
    WHERE col = v_order_no;

EXCEPTION
WHEN NO_DATA_FOUND THEN
     dbms_output.put_line('ndf');
WHEN OTHERS THEN
     dbms_output.put_line('Error');
END;

3 个答案:

答案 0 :(得分:3)

正确的例外是VALUE_ERROR。但是,OTHERS也应该捕获该错误。你的代码的问题是异常被抛出在块的声明部分。如果您在BEGIN之后移动该作业,则应该能够捕获该异常。

DECLARE
    v_order_no NUMBER(10);
    var NUMBER(10);
BEGIN
    v_order_no := &Order_Number;
    SELECT 1 INTO var
    FROM tbl
    WHERE col = v_order_no;

EXCEPTION
  WHEN NO_DATA_FOUND THEN
     dbms_output.put_line('ndf');
  WHEN VALUE_ERROR THEN
     dbms_output.put_line('value_error');
  WHEN OTHERS THEN
     dbms_output.put_line('Error');
END;

答案 1 :(得分:2)

我会给赋值赋予它自己的子块,这样你就可以保证任何验证错误来自那个,而不是代码的其他部分。

我还会将&order_number括在单引号中,以防它是一个字符串,可能导致无效的PL / SQL和编译错误,而不是运行时错误。

declare
    v_order_no number(10);
    var        number(10);
begin
    begin
        v_order_no := '&order_number';
    exception
        when value_error then
            raise_application_error
            ( -20000, '"&order_number" is not a numeric order number', true);
    end;

    select 1 into var from dual where v_order_no > 0;
    dbms_output.put_line('var = ' || var);

exception
    when no_data_found then
        dbms_output.put_line('ndf');
end;

现在,如果您使用order_number = 123x运行它,则作业v_order_no := '123x'将完全失败:

ORA-20000: "123x" is not a numeric order number
ORA-06512: at line 9
ORA-06502: PL/SQL: numeric or value error: character to number conversion error

如果不加引号,则无法编译:

        v_order_no := 123x
                         *
ERROR at line 6:
ORA-06550: line 6, column 26:
PLS-00103: Encountered the symbol "X" when expecting one of the following:
* & = - + ; < / > at in is mod remainder not rem
<an exponent (**)> <> or != or ~= >= <= <> and or like like2
like4 likec between || multiset member submultiset
The symbol "; was inserted before "X" to continue.

答案 2 :(得分:1)

添加额外的BeginEND块应解决您的问题,但应该捕获异常,但@pablomatico建议的是写入块的正确方法。如果你想坚持自己的代码,你可以这样做:

BEGIN

DECLARE
    v_order_no NUMBER(10) := &Order_Number;
    var NUMBER(10);
BEGIN
    SELECT 1 INTO var
    FROM tbl
    WHERE col = v_order_no;

EXCEPTION
WHEN NO_DATA_FOUND THEN
     dbms_output.put_line('ndf');
WHEN OTHERS THEN
     dbms_output.put_line('Error');
END;

END;