Search code examples
oracleplsqlexceptionraiseplsqldeveloper

scope of raise exception, handling your own exceptions in PLSQL code


I have this procedure:

create or replace PROCEDURE CONVERTE
IS
    CURSOR oldemployees IS
        SELECT *
        FROM emp1
        WHERE data_saida= NULL;

    new_ndep emp1.num_dep%type;
  bi_inexistente   EXCEPTION;
  dep_inexistente   EXCEPTION;
  employeeNr    emp1.num_empregado%type;

BEGIN
    FOR old_emp IN oldemployees
    LOOP
  employeeNr:= old_emp.num_empregado;
        if (old_emp.bi = NULL) then
        raise bi_inexistente;   
    else  
      IF (old_emp.num_dep>20) THEN
                SELECT ndep_novo INTO new_ndep FROM Converte_dep WHERE ndep_antigo= old_emp.num_dep;
       elsif (old_emp.num_dep = NULL) then
            new_ndep:= 0;
            raise dep_inexistente;    
       end if; 
       INSERT INTO EMP2 VALUES (old_emp.bi, old_emp.nome, old_emp.morada, old_emp.data_entrada, old_emp.data_saida, new_ndep);
       COMMIT;
    end if; 
    end loop; 

EXCEPTION
when bi_inexistente then
  INSERT INTO ERROS VALUES(employeeNr, 'BI Inexistente');
  COMMIT;

when dep_inexistente then
  INSERT INTO ERROS VALUES(employeeNr, 'Departamento Inexistente');
  COMMIT;
end;

I want to do INSERT INTO EMP2 VALUES (old_emp.bi, old_emp.nome, old_emp.morada, old_emp.data_entrada, old_emp.data_saida, new_ndep); even after the raising dep_inexistente, but after reading oracle's reference, I'm a little bit confused; Basically, when it's null, I want to not do that insert, otherwise I want to insert, even when department number is null (which I turn to 0).

So, is the code getting it right or how should I raise my exceptions or handle pre-defined exceptions for my case?


Solution

  • I don't think exceptions should be used as an inelegant GOTO statement. If you want to structure your code you could use procedures (and subprocedures). If the work is done at one place in the code just use the RETURN statement. Catch exceptions only when that makes sense.