Thursday, April 24, 2008

exception in plsql

PL sql的exception必须是放在Begin和end块中, 而且每个begin-end 块中只能有一个exception. 这并不表示一个存储过程只能有一个exception.



通常的写法是:


BEGIN
SELECT price / earnings INTO pe_ratio FROM stocks
WHERE symbol = 'XYZ'; -- might cause division-by-zero error
INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio);
COMMIT;
EXCEPTION -- exception handlers begin
WHEN ZERO_DIVIDE THEN -- handles 'division by zero' error
INSERT INTO stats (symbol, ratio) VALUES ('XYZ', NULL);
COMMIT;
...
WHEN OTHERS THEN -- handles all other errors
ROLLBACK;
END; -- exception handlers and block end here





一个存储过程中包含多个exception handler的写法是:




BEGIN
DELETE FROM stats WHERE symbol = 'XYZ';
BEGIN ---------- sub-block begins
SELECT price / NVL(earnings, 0) INTO pe_ratio FROM stocks
WHERE symbol = 'XYZ';
EXCEPTION
WHEN ZERO_DIVIDE THEN
pe_ratio := 0;
END; ---------- sub-block ends


INSERT INTO stats (symbol, ratio) VALUES ('XYZ', pe_ratio);
EXCEPTION
WHEN OTHERS THEN
...
END;





我们也可以主动的抛出一个异常, 语法和Pascal出奇的一致. 下面代码是先定义了一个past_due异常类型, 然后在代码中主动抛出一个past_due异常.



Exceptions can be declared only in the declarative part of a PL/SQL block, subprogram, or package. You declare an exception by introducing its name, followed by the keyword EXCEPTION. In the following example, you declare an exception named past_due:


DECLARE


past_due EXCEPTION;


begin


...


if ... then


RAISE past_due; -- this is not handled


end if;


,,


end;

No comments:

CNOUG.net