Frequently I see questions and issues around the use of Exception/Error Handling in PL/SQL. More often than not the issue comes from the questioners misunderstanding about how PL/SQL is constructed and executed, so I thought I'd write a small article covering the key concepts to give a clear picture of how it all hangs together. (Note: the examples are just showing examples of the exception handling structure, and should not be taken as truly valid code for ways of handling things)

Exception Handling

Contents1. Understanding Execution Blocks (part 1)2. Execution of the Execution Block3. Exceptions4. Understanding Execution Blocks (part 2)5. How to continue exection of statements after an exception6. User defined exceptions7. Line number of exception8. Exceptions within code within the exception block

1. Understanding Execution Blocks (part 1)The first thing that one needs to understand is almost taking us back to the basics of PL/SQL... how a PL/SQL execution block is constructed.

(Note: The same can also be done for packages, but let's keep it simple)

2. Execution of the Execution BlockThis may seem a simple concept, but it's surprising how many people have issues showing they haven't grasped it. When an Execution block is entered, the declaration section is processed, creating a scope of variables, types , cursors, etc. to be visible to the execution block and then execution enters into the Statements section. Each statment in the statements section is executed in turn and when the execution completes the last statment the execution block is exited back to whatever called it.

3. ExceptionsExceptions generally happen during the execution of statements in the Statements section. When an exception happens the execution of statements jumps immediately into the exception section. In this section we can specify what exceptions we wish to 'capture' or 'trap' and do one of the two following things...

(Note: The exception section still has access to all the declared items in the declaration section)

3.i) Handle the exceptionWe do this when we recognise what the exception is (most likely it's something we expect to happen) and we have a means of dealing with it so that our application can continue on.

Example...

(without the exception handler the exception is passed back to the calling code, in this case SQL*Plus)

3.ii) Raise the exceptionWe do this when:-a) we recognise the exception, handle it but still want to let the calling code know that it happenedb) we recognise the exception, wish to log it happened and then let the calling code deal with itc) we don't recognise the exception and we want the calling code to deal with it

As you can see from the sql_errors log table, no log was written so the WHEN others exception was the exception that raised the error to the calling code (SQL*Plus)

4. Understanding Execution Blocks (part 2)Ok, so now we understand the very basics of an execution block and what happens when an exception happens. Let's take it a step further...

Execution blocks are not just a single simple block in most cases. Often, during our statements section we have a need to call some reusable code and we do that by calling a procedure or function. Effectively this nests the procedure or function's code as another execution block within the current statement section so, in terms of execution, we end up with something like...

5. How to continue exection of statements after an exceptionOne of the common questions asked is how to return execution to the statement after the one that created the exception and continue on.

Well, firstly, you can only do this for statements you expect to raise an exception, such as when you want to check if there is no data found in a query.

If you consider what's been shown above you could put any statement you expect to cause an exception inside it's own procedure or function with it's own exception section to handle the exception without raising it back to the calling code. However, the nature of procedures and functions is really to provide a means of re-using code, so if it's a statement you only use once it seems a little silly to go creating individual procedures for these.

Instead, you nest execution blocks directly, to give the same result as shown in the diagram at the start of part 4 of this article.

You can see from this that, very simply, the code that we expected may have an exception was able to either handle the exception and return to the outer execution block to continue execution, or if an unexpected exception occurred then it was able to be raised up to the outer exception section.

6. User defined exceptionsThere are three sorts of 'User Defined' exceptions. There are logical situations (e.g. business logic) where, for example, certain criteria are not met to complete a task, and there are existing Oracle errors that you wish to give a name to in order to capture them in the exception section. The third is raising your own exception messages with our own exception numbers. Let's look at the first one...

Let's say I have tables which detail stock availablility and reorder levels...

Now, our Business has told the administrative clerk to check stock levels and re-order anything that is below the re-order level, but not to hold stock of more than 4 times the re-order level for any particular item. As an IT department we've been asked to put together an application that will automatically produce the re-order documents upon the clerks request and, because our company is so tight-ar*ed about money, they don't want to waste any paper with incorrect printouts so we have to ensure the clerk can't order things they shouldn't.

That's better. And now we don't have to use all those nested IF statements and worry about it accidently getting to code that will print the order out as, once one of our user defined exceptions is raised, execution goes from the Statements section into the Exception section and all handling of errors is done in one place.

Now for the second sort of user defined exception...

A new requirement has come in from the Finance department who want to have details shown on the order that show a re-order 'indicator' based on the formula ((maximum allowed stock - current stock)/re-order quantity), so this needs calculating and passing to the report...

*ERROR at line 1:ORA-01476: divisor is equal to zeroORA-06512: at "SCOTT.RE_ORDER", line 17ORA-06512: at line 1

SQL>

Hmm, there's a problem if the person specifies a re-order quantity of zero. It raises an unhandled exception.Well, we could put a condition/check into our code to make sure the parameter is not zero, but again we would be wrapping our code in an IF statement and not dealing with the exception in the exception handler.

We could do as we did before and just include a simple IF statement to check the value and raise our own user defined exception but, in this instance the error is standard Oracle error (ORA-01476) so we should be able to capture it inside the exception handler anyway... however...

EXCEPTION WHEN ORA-01476 THEN

... is not valid. What we need is to give this Oracle error a name.

This is done by declaring a user defined exception as we did before and then associating that name with the error number using the PRAGMA EXCEPTION_INIT statement in the declaration section.

*ERROR at line 1:ORA-20001: Quantity specified is too much. Max for this item: 78ORA-06512: at "SCOTT.RE_ORDER", line 42ORA-06512: at line 1

SQL> exec re_order(3,40);BEGIN re_order(3,40); END;

*ERROR at line 1:ORA-20000: Stock has not reached re-order level yet!ORA-06512: at "SCOTT.RE_ORDER", line 42ORA-06512: at line 1

SQL>

As you can see from this we have raised exceptions with our own error numbers. You can use any number from -20000 to -20999 for your own error messages.

As with previous examples, these error numbers can be associated with exception names using the EXCEPTION datatypes and the PRAGMA EXCEPTION_INIT statements in the declaration section.

So there we have it, capturing existing Oracle errors and handling business logic through raising exceptions of our own.

7. Line number / Source of exceptionOne of the common problems people experience when they use exceptions is actually knowing which line of their code the error occured on. The problem here is that when you include an exception section in your execution block and then you raise an error from there to the calling code, the calling code sees the exception as having orginated from the line of code in the exception section that raised the error rather than the original line of code. Look at that last example from the previous section of this article. It shows that the error happened on line 42 of the re_order procedure, but if we look at line 42, that is the RAISE; statement in the exception block, not the actual line of code where the exception happened.

So how do we find out where the error occurred?

One answer (perhaps the simplest) is to remove the actual exception handler that is dealing with that error...

*ERROR at line 1:ORA-20000: Stock has not reached re-order level yet!ORA-06512: at "SCOTT.RE_ORDER", line 24ORA-06512: at line 1

SQL>

Now, because the code is not capturing the exception itself, the original line number is passed up until it gets to a point where it is handled (in this case where it is displayed by SQL*Plus)

An alternative is to use the DBMS_UTILITY.FORMAT_ERROR_BACKTRACE function. Whilst this doesn't provide the error itself, it does provide a full trace back through execution blocks to the source of the error.

*ERROR at line 1:ORA-20000: Stock has not reached re-order level yet!ORA-06512: at "SCOTT.RE_ORDER", line 43ORA-06512: at line 1

SQL>

Another issue often encountered is when there are nested execution blocks that raise, capture, raise again etc. the exceptions. It can be quite messy to keep track of the source of an error, so a good error logging mechanism writing the error information as it happens to a table using autonomous transactions and the information in the DBMS_UTILITY.FORMAT_ERROR_BACKTRACE is a well worthwhile method of dealing with this

In summary there are various means and methods for tracing where the exception occurred and which method you use depends on your own requirements and needs for logging and/or handling errors.

8. Exceptions within code within the exception blockThis last section of the article is just a light finishing touch to it really.What happens when an exception occurs inside the exception section of the execution block?

Well it's quite simple really, if you haven't figured it out already...

There are two things that will happen... either...

a) The exception will be raised up to the exception handler of the calling execution block to be dealt with...

begin*ERROR at line 1:ORA-20000: nesting level 1 exceptionORA-06512: at line 18ORA-20000: nesting level 2 exceptionORA-01476: divisor is equal to zeroORA-01403: no data found

SQL>

From this example you can see that the exception that happened on line 7 (within the exception handler) has prevented the continuing execution of the code in that exception handler and has raised the exception straight back to the nested level above (2 in this case), although we do still have the "no data found" exception on the error stack so we can detect two errors at once. Smart eh!

b) The other thing that can happen is if the exception handler itself has a nested execution block...

By the way, I wouldn't recommend using WHEN OTHERS THEN NULL; in production code otherwise you'll prevent any real errors from being found and probably get the sack. I just did it to demonstrate.

OK. Well I hope that's given some insight into Exceptions and Exception handling for those who need to know. Turned out to be a slightly larger article than I intended, but I think it covers most of the basics.