Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `EXCEPTION WHEN OTHERS THEN RAISE` do something?

Being still a newbie in PL/SQL, I've been copying and pasting around the following trigger:

CREATE OR REPLACE TRIGGER FOO_TRG1
    BEFORE INSERT
    ON FOO
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
BEGIN
    IF :NEW.FOO_ID IS NULL THEN
        SELECT FOO_SEQ1.NEXTVAL INTO :NEW.FOO_ID FROM DUAL;
    END IF;

    EXCEPTION
        WHEN OTHERS THEN RAISE;
END FOO_TRG1;
/
ALTER TRIGGER FOO_TRG1 ENABLE;

I suspect that the included exception handling code does nothing at all and could simply get removed, since I'll get an error message anyway if something goes wrong. Am I right?

(I guess such code is the result of further editing prior code.)

like image 439
Álvaro González Avatar asked Feb 04 '13 11:02

Álvaro González


People also ask

What is the purpose of using others exception?

The WHEN OTHERS clause is used to trap all remaining exceptions that have not been handled by your Named System Exceptions and Named Programmer-Defined Exceptions.

Can an exception section have raise statement?

You can code a RAISE statement for a given exception anywhere within the scope of that exception. When an exception is raised, if PL/SQL cannot find a handler for it in the current block, the exception propagates to successive enclosing blocks, until a handler is found or there are no more blocks to search.

What type of exception requires a raise statement?

The RAISE statement stops normal execution of a PL/SQL block or subprogram and transfers control to an exception handler. RAISE statements can raise predefined exceptions, such as ZERO_DIVIDE or NO_DATA_FOUND , or user-defined exceptions whose names you decide.

When others exception handler should be placed where?

The optional OTHERS exception handler, which is always the last handler in a block or subprogram, acts as the handler for all exceptions not named specifically. Thus, a block or subprogram can have only one OTHERS handler.


1 Answers

yes, that exception does nothing but raise the same error out. also it serves to mask the real line number of the error. i'd remove that if I were you.

eg:

SQL> declare
  2    v number;
  3  begin
  4    select 1 into v from dual;
  5    select 'a' into v from dual;
  6  exception
  7    when others
  8    then
  9      raise;
 10  end;
 11  /
declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 9

vs:

SQL> declare
  2    v number;
  3  begin
  4    select 1 into v from dual;
  5    select 'a' into v from dual;
  6  end;
  7  /
declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 5

the line number in the first one is pointing to the raise instead of the real line number. it can make tracking down errors harder.

like image 133
DazzaL Avatar answered Oct 26 '22 14:10

DazzaL