browse: forums | FAQ
Connecting Tech Pros Worldwide

EXCEPTIONS - 3

debasisdas's Avatar
Moderator
 
Join Date: Dec 2006
Location: Bangalore ,India
Posts: 7,578
#1   Jun 2 '07
EXAMPLE SHOWING USE OF USER DEFINED EXCEPTION
==============================================
Expand|Select|Wrap|Line Numbers
  1. DECLARE
  2. M NUMBER(4);
  3. MYERROR EXCEPTION;
  4. BEGIN
  5. SELECT COMM INTO M FROM EMP WHERE EMPNO=7788;
  6. IF M IS NULL THEN
  7. RAISE MYERROR;
  8. END IF;
  9. EXCEPTION
  10. WHEN NO_DATA_FOUND THEN
  11. DBMS_OUTPUT.PUT_LINE('ERROR OF DATA......!');
  12. WHEN TOO_MANY_ROWS THEN
  13. DBMS_OUTPUT.PUT_LINE('ERROR OF TOOMANY ROWS.....!');
  14. WHEN MYERROR THEN
  15. DBMS_OUTPUT.PUT_LINE('ERROR FOUND NULL......!');
  16. END;
  17.  
USER DEFINED EXCEPTION----Used to raise an exception explicitely. Must be declared in the declaration section and handled in the expeption block.

EXAMPLE SHOWING USE OF USER DEFINED EXCEPTION
==============================================
Expand|Select|Wrap|Line Numbers
  1.  DECLARE
  2.  SALARY EMP.SAL%TYPE;
  3.  NAME EMP.ENAME%TYPE;
  4.  NO NUMBER:=&NO;
  5.  GREATER EXCEPTION;   --User defined exception
  6.  LESSER EXCEPTION;    --User defined exception
  7.  BEGIN
  8.  SELECT ENAME,SAL INTO NAME,SALARY FROM EMP WHERE  EMPNO=NO;
  9.  IF SALARY>2000 THEN
  10.  RAISE GREATER;   --User defined exception raised explicitely.
  11.  ELSE
  12.  RAISE LESSER;     --User defined exception raised explicitely.
  13.  END IF;
  14.  EXCEPTION
  15.  WHEN GREATER THEN
  16.  RAISE_APPLICATION_ERROR(-20001,'YOUR SALARY IS MORE  THAN 2000');
  17. --User defined exception handled here.
  18.  WHEN LESSER THEN
  19.  RAISE_APPLICATION_ERROR(-20002,'YOUR SALARY IS LESS   THAN 2000');
  20. --User defined exception handled here.
  21.  WHEN NO_DATA_FOUND THEN
  22.  RAISE_APPLICATION_ERROR(-20003,'PLEASE   ENTER A VALID  EMPNO');
  23.  END;
  24.  
NOTE--Both predeined and userdefined exceptions can be handled in a single exception block.

USER DEFINED EXCEPTION FOR ORACLE DEFINED NUMBER
=================================================
Expand|Select|Wrap|Line Numbers
  1. DECLARE
  2. EXP1 EXCEPTION;
  3. PRAGMA EXCEPTION_INIT(EXP1,-00001);   --exp1 is initialized to error number 00001
  4. BEGIN
  5. INSERT INTO DEPT VALUES(&DNO,'&DNAME','&LOC');
  6. DBMS_OUTPUT.PUT_LINE('ONE RECORD INSERTED');
  7. EXCEPTION
  8. WHEN EXP1 THEN
  9. DBMS_OUTPUT.PUT_LINE('DUPLICATE VALUE');
  10. --when the exception 00001 is raised instead of showing oracle defined message user defined message is displayed.
  11. END;
  12.  
  13.  
A pragma is a compiler directive that is processed at compile time, not at run time.
The pragma must appear somewhere after the exception declaration in the same declarative section.


Also check EXCEPTIONS - 4

Last edited by debasisdas; Feb 12 '08 at 10:26 AM. Reason: Some changes.



Reply