The execution of the statement may cause a loss or even a system crash due to an exception. To avoid this, exceptions must be processed. Pl/sql provides a way to handle exceptions. This method will automatically move to the exception handling section whenever an exception error occurs during the execution of the Pl/sql code section.
1. Predefined exceptions
Predefined exceptions are generated by the system. For example, in the presence of 0 divisor, the system produces a predefined zero_divide exception. Examples are as follows:
DECLARE
num1 Number: = 2;
Num2 number: = 0;
NUM3 number;
Begin
Num3: = num1/num2--When executing this sentence, the system catches the exception automatically to the exception processing part, the final output
"cannot divide 0".
exception when
zero_divide then
dbms_output.put_line (' cannot except 0 ');
When Too_many_rows then
dbms_output.put_line (' Too many rows ');
End
If there is no code to handle the exception in the current block, and the begin/end block is nested, the program continues to look for the code block in the outer block to handle the exception until one is found. If a block of code that does not eventually handle the exception exists, the program ends. When the exception is processed, the program continues executing the code after the exception code block.
2, custom exception
If the user needs to customize the exception, you can define a exception variable and then use the raise statement to throw an exception, and then catch the corresponding throw exception when catching the exception. The sample code is as follows:
DECLARE
selfdefineexception Exception/* Define exception variable * *
num1 number: = 2;
Num2 Number: = 3;
NUM3 number;
Begin
Num3: = Num1 + num2;
If Num3=5 then
raise selfdefineexception/* throws the custom exception/end
if;
Exception when
selfdefineexception then/* Captures a custom exception * *
dbms_output.put_line ("selfdefineexception");
When Zero_divide then
dbms_output.put_line ("not except 0");
End
3. Use others exception
For exceptions that are not caught directly, the others exception can be used to catch, others exceptions can be used alone, but must be placed at the end of all cases when used with other exception handling. The sample code is as follows:
DECLARE
num1 Number: = 2;
Num2 number: = 0;
NUM3 number;
Begin
Num3: = num1/num2--When executing this sentence, the system catches the exception automatically to the exception processing part, the final output
"cannot divide 0".
exception when
others then/* Here Direct capture others anomaly * *
dbms_output.put_line (' not except 0 ');
End
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/database/Oracle/