我正在尝试在我的oracle PL / SQL程序中生成DIVIDE_BY_ZERO异常。我使用函数但是当我运行我的程序时,我收到错误,如下所示。谁能告诉我程序中有什么问题?
代码:
CREATE OR REPLACE
PACKAGE CALCULATOR AS
FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER;
FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER;
END CALCULATOR;
/
CREATE OR REPLACE
PACKAGE BODY CALCULATOR AS
FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER AS
BEGIN
return addend + addend2;
END AddNumber;
FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER AS
BEGIN
return divend / divend2;
EXCEPTION
WHEN ZERO_DIVIDE THEN
NULL;
END DivNumber;
END CALCULATOR;
/
select calculator.AddNumber(3,4) from dual;
select calculator.DivNumber(12,0) from dual;
输出:
答案 0 :(得分:1)
你可以处理像这样的例外
FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER AS
e_ZERO_DIVIDE EXCEPTION;
BEGIN
-- the condition
IF divend2 = 0 THEN
Raise e_ZERO_DIVIDE;
END IF;
return divend / divend2;
--Exception handling
EXCEPTION
WHEN e_ZERO_DIVIDE THEN
dbms_output.put_line('Division by 0 or null');
RETURN 1;
WHEN OTHERS THEN
dbms_output.put_line('ERROR: '||sqlerrm);
RETURN 1;
END DivNumber;
答案 1 :(得分:0)
IMO你永远不应该写出引发可避免异常的代码。有时你可能无法避免提出异常但在这种情况下你可以。我建议您按如下方式重写您的功能:
FUNCTION DivNumber(numerator IN Number, denominator IN Number) RETURN NUMBER AS
BEGIN
IF NVL(denominator, 0) <> 0 THEN
return numerator / denominator;
ELSE
RETURN NULL;
END IF;
END DivNumber;
祝你好运。