General Exception Handling
Hello. In my applications I usually have a try catch(Throwable) block surrounding all the top code (the code in main()) to log and report errors and exceptions that is not caught anywhere else, and to have my application exit in a controlled way. But I recently noticed that exceptions thrown in event handling (i.e. java.awt.EventDispatchThread.run) are not caught by the try catch block in main().
Are there any easy way to catch everything so my app can exit in a controlled way?
If this is not possible which exceptions are not propagated to main()? I would guess that it's exceptions thrown in other threads, is this correct? If so, do I have to surround all event handling by try catch(Throwable) to be safe?
I would like more information and guidelines about exception handling. Any book recommendations?
Help appreciated, thanks!
You should never let exceptions propagate outside your event handling methods.
If you don't follow that rule, the java.awt.EventDispatchThread.run() method terminates and the Java Virtual Machine tries to print the stack trace to the terminal window (if there is one) and then exits, but not through your main() method.
So, try /catch all Exceptions inside your event handler methods:
// inside event handler method
try {
// handle event here
} catch (Throwable t) {
// handle errors and recover from errors here
// and either log error or if important display message to the user.
}There is no easy-lazy way to do exception handling by only having the try/catch block in main in this case.
Note : If any of the listeners throws an exception none of the following listeners is called. Since there is no guarantee of the order in which listeners are called you cannot be sure which ones are called first.
Similar Messages
-
Exception handling - general concepts
ok, well i skipped the chapter on exception handling :=)
Correct me if im wrong, but lets say im writing some code and im not sure how to handle some of the exceptions that might get thrown or what exceptions will get thrown for that matter. How does one go about handling every possible exception that is "required".
I guess what im trying to ask is that if a certain block of code is calling methods that throw specific exceptions, then you will need to handle those exceptions. So that means you need to be aware of, or know to go lookup the possible exceptions that those methods can throw.
Im skipping around in Beginning Java 2, from wronx press jdk 1.4 editionThis is quite a hard one to be specific on as I think most of us learned this with a bit of trial and error.
1. IO always requires the method to be thrown ie
public void writeContents() throws IOException {
// methods
2. The compiler will tell you when you need a try /catch block
3. I often code this with;-
try {
// my methods here;
catch (Exception ignore) {}
and have empty braces with a general catch all Exception on the first run
4. Then if there are problems such as the code won't work I fill in the blanks ie;-
catch (Exception e) {System.out.println(e);}
// or e.getMessage() );
// or printStackTrace();
depending on what the first message is
5. Correct the exception now that you know what it is. Really this is a form of 'divide and conquer' as you eliminate the problems as they occur through javas exception handling abilities.
6. With a bit more practice you will implement things like finally and know when to put the handler back to 'catch (Exception ignore) {}' and when to leave it in.
7. Exception handling can also be used to instruct the client in useful ways too eg;-
try {
myTextfield.setText("Enter Your Age");
myInt = parse ...(myTextfield.getText(etc ...
catch (NumberFormatException nfe) {
myTextfield.setText("Enter Number Values Only");
// or something like
catch (NullPointerException nfe) {
myTextfield.setText("Oops you forgot to enter a value");
This has been my experience anyway + I trust I have assisted -
PL/SQL 101 : Exception Handling
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
Contents
1. Understanding Execution Blocks (part 1)
2. Execution of the Execution Block
3. Exceptions
4. Understanding Execution Blocks (part 2)
5. How to continue exection of statements after an exception
6. User defined exceptions
7. Line number of exception
8. 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.
Essentially an execution block is made of 3 sections...
+---------------------------+
| Declaration Section |
+---------------------------+
| Statements Section |
+---------------------------+
| Exception Section |
+---------------------------+
The Declaration section is the part defined between the PROCEDURE/FUNCTION header or the DECLARE keyword (for anonymous blocks) and the BEGIN keyword. (Optional section)
The Statements section is where your code goes and lies between the BEGIN keyword and the EXCEPTION keyword (or END keyword if there is no EXCEPTION section). (Mandatory section)
The Exception section is where any exception handling goes and lies between the EXCEPTION keyword at the END keyword. (Optional section)
Example of an anonymous block...
DECLARE
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
Example of a procedure/function block...
[CREATE OR REPLACE] (PROCEDURE|FUNCTION) <proc or fn name> [(<parameters>)] [RETURN <datatype>] (IS|AS)
.. declarative statements go here ..
BEGIN
.. code statements go here ..
EXCEPTION
.. exception handlers go here ..
END;
(Note: The same can also be done for packages, but let's keep it simple)
2. Execution of the Execution Block
This 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. Exceptions
Exceptions 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 exception
We 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)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
(with an exception handler, we capture the exception, handle it how we want to, and the calling code is happy that there is no error for it to report)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 begin
4 select ename
5 into v_name
6 from emp
7 where empno = &empno;
8 dbms_output.put_line(v_name);
9 exception
10 when no_data_found then
11 dbms_output.put_line('There is no employee with this employee number.');
12* end;
SQL> /
Enter value for empno: 123
old 7: where empno = &empno;
new 7: where empno = 123;
There is no employee with this employee number.
PL/SQL procedure successfully completed.
3.ii) Raise the exception
We do this when:-
a) we recognise the exception, handle it but still want to let the calling code know that it happened
b) we recognise the exception, wish to log it happened and then let the calling code deal with it
c) we don't recognise the exception and we want the calling code to deal with it
Example of b)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16* end;
SQL> /
Enter value for empno: 123
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 123;
declare
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 15
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
Example of c)
SQL> ed
Wrote file afiedt.buf
1 declare
2 v_name VARCHAR2(20);
3 v_empno NUMBER := &empno;
4 begin
5 select ename
6 into v_name
7 from emp
8 where empno = v_empno;
9 dbms_output.put_line(v_name);
10 EXCEPTION
11 WHEN no_data_found THEN
12 INSERT INTO sql_errors (txt)
13 VALUES ('Search for '||v_empno||' failed.');
14 COMMIT;
15 RAISE;
16 WHEN others THEN
17 RAISE;
18* end;
SQL> /
Enter value for empno: 'ABC'
old 3: v_empno NUMBER := &empno;
new 3: v_empno NUMBER := 'ABC';
declare
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 3
SQL> select * from sql_errors;
TXT
Search for 123 failed.
SQL>
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...
+---------------------------------+
| Declaration Section |
+---------------------------------+
| Statements Section |
| . |
| +---------------------------+ |
| | Declaration Section | |
| +---------------------------+ |
| | Statements Section | |
| +---------------------------+ |
| | Exception Section | |
| +---------------------------+ |
| . |
+---------------------------------+
| Exception Section |
+---------------------------------+
Example... (Note: log_trace just writes some text to a table for tracing)
SQL> create or replace procedure a as
2 v_dummy NUMBER := log_trace('Procedure A''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure A''s Statement Section');
5 v_dummy := 1/0; -- cause an exception
6 exception
7 when others then
8 v_dummy := log_trace('Procedure A''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> create or replace procedure b as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 a; -- HERE the execution passes to the declare/statement/exception sections of A
6 exception
7 when others then
8 v_dummy := log_trace('Procedure B''s Exception Section');
9 raise;
10 end;
11 /
Procedure created.
SQL> exec b;
BEGIN b; END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.B", line 9
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Procedure A's Declaration Section
Procedure A's Statement Section
Procedure A's Exception Section
Procedure B's Exception Section
6 rows selected.
SQL>
Likewise, execution blocks can be nested deeper and deeper.
5. How to continue exection of statements after an exception
One 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.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure b (p_empno IN VARCHAR2) as
2 v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
3 begin
4 v_dummy := log_trace('Procedure B''s Statement Section');
5 -- Here we start another execution block nested in the first one...
6 declare
7 v_dummy NUMBER := log_trace('Nested Block Declaration Section');
8 begin
9 v_dummy := log_trace('Nested Block Statement Section');
10 select empno
11 into v_dummy
12 from emp
13 where empno = p_empno; -- Note: the parameters and variables from
parent execution block are available to use!
14 exception
15 when no_data_found then
16 -- This is an exception we can handle so we don't raise it
17 v_dummy := log_trace('No employee was found');
18 v_dummy := log_trace('Nested Block Exception Section - Exception Handled');
19 when others then
20 -- Other exceptions we can't handle so we raise them
21 v_dummy := log_trace('Nested Block Exception Section - Exception Raised');
22 raise;
23 end;
24 -- ...Here endeth the nested execution block
25 -- As the nested block handled it's exception we come back to here...
26 v_dummy := log_trace('Procedure B''s Statement Section Continued');
27 exception
28 when others then
29 -- We'll only get to here if an unhandled exception was raised
30 -- either in the nested block or in procedure b's statement section
31 v_dummy := log_trace('Procedure B''s Exception Section');
32 raise;
33* end;
SQL> /
Procedure created.
SQL> exec b(123);
PL/SQL procedure successfully completed.
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
No employee was found
Nested Block Exception Section - Exception Handled
Procedure B's Statement Section Continued
7 rows selected.
SQL> truncate table code_trace;
Table truncated.
SQL> exec b('ABC');
BEGIN b('ABC'); END;
ERROR at line 1:
ORA-01722: invalid number
ORA-06512: at "SCOTT.B", line 32
ORA-06512: at line 1
SQL> select * from code_trace;
TXT
Procedure B's Declaration Section
Procedure B's Statement Section
Nested Block Declaration Section
Nested Block Statement Section
Nested Block Exception Section - Exception Raised
Procedure B's Exception Section
6 rows selected.
SQL>
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 exceptions
There 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...
SQL> select * from reorder_level;
ITEM_ID STOCK_LEVEL
1 20
2 20
3 10
4 2
5 2
SQL> select * from stock;
ITEM_ID ITEM_DESC STOCK_LEVEL
1 Pencils 10
2 Pens 2
3 Notepads 25
4 Stapler 5
5 Hole Punch 3
SQL>
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.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 begin
11 OPEN cur_stock_reorder;
12 FETCH cur_stock_reorder INTO v_stock;
13 IF cur_stock_reorder%NOTFOUND THEN
14 RAISE no_data_found;
15 END IF;
16 CLOSE cur_stock_reorder;
17 --
18 IF v_stock.stock_level >= v_stock.reorder_level THEN
19 -- Stock is not low enough to warrant an order
20 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
21 ELSE
22 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
23 -- Required amount is over-ordering
24 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
25 ELSE
26 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
27 -- Here goes our code to print the order
28 END IF;
29 END IF;
30 --
31 exception
32 WHEN no_data_found THEN
33 CLOSE cur_stock_reorder;
34 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
35* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
Ok, so that code works, but it's a bit messy with all those nested IF statements. Is there a cleaner way perhaps? Wouldn't it be nice if we could set up our own exceptions...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 from stock s join reorder_level r on (s.item_id = r.item_id)
7 where s.item_id = p_item_id;
8 --
9 v_stock cur_stock_reorder%ROWTYPE;
10 --
11 -- Let's declare our own exceptions for business logic...
12 exc_not_warranted EXCEPTION;
13 exc_too_much EXCEPTION;
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 RAISE exc_not_warranted;
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29 RAISE exc_too_much;
30 END IF;
31 --
32 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
33 -- Here goes our code to print the order
34 --
35 exception
36 WHEN no_data_found THEN
37 CLOSE cur_stock_reorder;
38 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
39 WHEN exc_not_warranted THEN
40 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
41 WHEN exc_too_much THEN
42 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
43* end;
SQL> /
Procedure created.
SQL> exec re_order(10,100);
Invalid Item ID.
PL/SQL procedure successfully completed.
SQL> exec re_order(3,40);
Stock has not reached re-order level yet!
PL/SQL procedure successfully completed.
SQL> exec re_order(1,100);
Quantity specified is too much. Max for this item: 70
PL/SQL procedure successfully completed.
SQL> exec re_order(2,50);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL>
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...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 begin
16 OPEN cur_stock_reorder;
17 FETCH cur_stock_reorder INTO v_stock;
18 IF cur_stock_reorder%NOTFOUND THEN
19 RAISE no_data_found;
20 END IF;
21 CLOSE cur_stock_reorder;
22 --
23 IF v_stock.stock_level >= v_stock.reorder_level THEN
24 -- Stock is not low enough to warrant an order
25 RAISE exc_not_warranted;
26 END IF;
27 --
28 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
29 -- Required amount is over-ordering
30 RAISE exc_too_much;
31 END IF;
32 --
33 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
34 -- Here goes our code to print the order, passing the finance_factor
35 --
36 exception
37 WHEN no_data_found THEN
38 CLOSE cur_stock_reorder;
39 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
40 WHEN exc_not_warranted THEN
41 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
42 WHEN exc_too_much THEN
43 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
44* end;
SQL> /
Procedure created.
SQL> exec re_order(2,40);
Order OK. Printing Order...
PL/SQL procedure successfully completed.
SQL> exec re_order(2,0);
BEGIN re_order(2,0); END;
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "SCOTT.RE_ORDER", line 17
ORA-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.
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 -- Let's declare our own exceptions for business logic...
13 exc_not_warranted EXCEPTION;
14 exc_too_much EXCEPTION;
15 --
16 exc_zero_quantity EXCEPTION;
17 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
18 begin
19 OPEN cur_stock_reorder;
20 FETCH cur_stock_reorder INTO v_stock;
21 IF cur_stock_reorder%NOTFOUND THEN
22 RAISE no_data_found;
23 END IF;
24 CLOSE cur_stock_reorder;
25 --
26 IF v_stock.stock_level >= v_stock.reorder_level THEN
27 -- Stock is not low enough to warrant an order
28 RAISE exc_not_warranted;
29 END IF;
30 --
31 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
32 -- Required amount is over-ordering
33 RAISE exc_too_much;
34 END IF;
35 --
36 DBMS_OUTPUT.PUT_LINE('Order OK. Printing Order...');
37 -- Here goes our code to print the order, passing the finance_factor
38 --
39 exception
40 WHEN exc_zero_quantity THEN
41 DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
42 WHEN no_data_found THEN
43 CLOSE cur_stock_reorder;
44 DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
45 WHEN exc_not_warranted THEN
46 DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
47 WHEN exc_too_much THEN
48 DBMS_OUTPUT.PUT_LINE('Quantity specified is too much. Max for this item: '
||to_char(v_stock.reorder_limit-v_stock.stock_level));
49* end;
SQL> /
Procedure created.
SQL> exec re_order(2,0);
Quantity of 0 (zero) is invalid.
PL/SQL procedure successfully completed.
SQL>
Lastly, let's look at raising our own exceptions with our own exception numbers...
SQL> ed
Wrote file afiedt.buf
1 create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
2 cursor cur_stock_reorder is
3 select s.stock_level
4 ,r.stock_level as reorder_level
5 ,(r.stock_level*4) as reorder_limit
6 ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
7 from stock s join reorder_level r on (s.item_id = r.item_id)
8 where s.item_id = p_item_id;
9 --
10 v_stock cur_stock_reorder%ROWTYPE;
11 --
12 exc_zero_quantity EXCEPTION;
13 PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
14 begin
15 OPEN cur_stock_reorder;
16 FETCH cur_stock_reorder INTO v_stock;
17 IF cur_stock_reorder%NOTFOUND THEN
18 RAISE no_data_found;
19 END IF;
20 CLOSE cur_stock_reorder;
21 --
22 IF v_stock.stock_level >= v_stock.reorder_level THEN
23 -- Stock is not low enough to warrant an order
24 [b]RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached re-order level yet!');[/b]
25 END IF;
26 --
27 IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
28 -- Required amount is over-ordering
29its nice article, have put up this one the blog
site,Nah, I don't have time to blog, but if one of the other Ace's/Experts wants to copy it to a blog with reference back to here (and all due credit given ;)) then that's fine by me.
I'd go for a book like "Selected articles by OTN members" or something. Does anybody have a list of links of all those mentioned articles?Just these ones I've bookmarked...
Introduction to regular expressions ... by CD
When your query takes too long ... by Rob van Wijk
How to pipeline a function with a dynamic number of columns? by ascheffer
PL/SQL 101 : Exception Handling by BluShadow -
Exception handling in rfcs and bapis
exception handling in rfcs and bapis
Hi Jayakrishna,
In General , there are non execptions in BAPIs, because of the reason, that the exception raised in a SAP envoronment may not mean anything for a non SAP initiator. All the exception situations would only fill the return table(TYpe BAPIRET2 or something like that). If you read that table after the call to the bapi, you can understand what has gone wrong.
Regards,
Ravi -
Exception Handling In BPEL By using Catch Blocks or Fault Policies Or Both
I have a confusion regarding
Exception handling :
When Should i go for 1)Catch Block (Remote , or binding ) in bpel for exception handling .
2)Fault Policy , Fault binding.xml
Currently iam using catch blocks , but even fault policy is good , but can i use both...
Currently in My bpel ,when any error occurs i have to send a error notification by Email .
Currently i have exposed the email service which shuts emails and write a file with errored Message.
Hence if any error i will catch i in a parent BPEL, i will just invoke the above email, service .
So anybody can help me by giving the suggestion how to go for the best approach
Edited by: anantwag on Mar 23, 2011 6:31 AMCurrently in My bpel ,when any error occurs i have to send a error notification by Email .
Currently i have exposed the email service which shuts emails and write a file with errored Message.Seeing your use case I will suggest you to use fault handling framework (fault policy). Fault handling framework should be used where you need generic error handling framework which handles all the faults occured in any composite component. Generally BPEL catch block should be used to propagate error info/fault back to the client/to fault handling framework or to consume an error
Regards,
Anuj -
In the current project my exception handling implementation is as follows :
Exception Handling Layer wise :
DL layer :
catch (Exception ex)
bool rethrow = ExceptionPolicy.HandleException(ex, "Ui Policy");
if (rethrow)
throw;
BL Layer
catch (Exception ex)
bool rethrow = ExceptionPolicy.HandleException(ex, "Ui Policy");
if (rethrow)
throw;
UI Layer
catch (Exception ex)
bool rethrow = ExceptionPolicy.HandleException(ex, "Ui Policy");
if (rethrow)
Response.Redirect("ErrorPage.aspx", false);
We have a tool to check the standards. And tool output is as follows :
The exception Exception should never been thrown. Always Subclass Exception and throw the subclassed Classes.
I need suggestions on how to implement the same according to standards.Your tool is wrong if it says to never throw Exception. This was a common recommendation back in the .NET v1 days but has long since been thrown out. It is perfectly fine to use Exception when you have a general exception that provides no information
that an application can use to make an informed opinion.
The general rules of exception throwing is to throw the most specific exception that makes sense. If there is no specific exception that applies and it would be useful for the caller to handle the exception differently than other exceptions then creating
a custom exception type is warranted. Otherwise throwing Exception is reasonable. As an example you might have an application that pulls back product data given an ID. There is no built in exception that says the ID is invalid. However an invalid ID
is something that an application may want to handle differently than, say, an exception about the product being discontinued. Therefore it might make sense to create an ItemNotFoundException exception that the application can react to.
Conversely there is no benefit in having different exception types for disk full and disk quota met. The application will respond the same in either case.
Michael Taylor
http://blogs.msmvps.com/p3net -
Integration Process exception handling & alerts, Java
Hello,
I would like to enhance my basic scenarios fool proof and with as much Java as possible.
I have set up several asynchronous and synchronous File to SOAP transfers between systems A and B
using PI70 including my own Java mapping classes and PI's AF_Modules beans. They work just fine.
I have not designed my own Integration Processes yet, so execution is based on channel settings and availability timing.
I have learned this aproach may be exposed to general faults resulting manual monitoring and repairing.
For example server problems at receiver side can result data losses as sender channel just keeps removing source
files like normally, as the process would be better to just stop right there and alert or something.
My question is, is the "Enterprise services Builders" Integration Process & Graphical definition screen the one and only tool to
customize whole process exception handling and alerts in PI, and Java is not an option?
Appreciate your advice on this.
Kind regards mHi m,
Strange Name
>>I have learned this aproach may be exposed to general faults resulting manual monitoring and repairing. For example server problems at receiver side can result data losses as sender channel just keeps removing source files like normally, as the process would be better to just stop right there and alert or something.
If you are looking to handle this particular scenario, then we have the alert mechanism and CCMS monitoring. There you will come to know whether the end system down or not.
Also in addition to this you can write your own java (in message mapping, as modules, java mapping) /abap code (as abap mapping, user exit in standard functions etc) for providing more details in error scenarios. But you need to validate whether the maintenance/development cost for the code is justified in your scenarios
Regards
Suraj -
hi,
I have created a custom component that has a service which invokes my custom java methods. I would like to redirect to two error pages depending on the exception thrown by the java method? How exception handling is done in UCM. I see a text box called error messages while creating the service and service actions. But that message is not printed when my java method throws application specific exceptions.
Is there a way to handle the exception at Service configuraration / UI side and redirect to two different meaningful error pages dependinf upon the thye of exception
Thanks,
SivaHi Jayakrishna,
In General , there are non execptions in BAPIs, because of the reason, that the exception raised in a SAP envoronment may not mean anything for a non SAP initiator. All the exception situations would only fill the return table(TYpe BAPIRET2 or something like that). If you read that table after the call to the bapi, you can understand what has gone wrong.
Regards,
Ravi -
Failover exception handling in partnerlink
Hi All,
I've been trying to test the failover exception handling feature in partnerlink and were not able to replicate it. Can you please assist me on this? Here is the steps which I've carried out:
1.) Develop a web service and deploy to my localhost's OC4J instance with the following ending point:
http://localhost:8888/plsqlwebService-webservice-context-root/plsqlwebserviceSoapHttpPort
2.) Develop the same web service and deploy it to my testing application server with the following ending point:
http://myappserver:8888/plsqlwebService-webservice-context-root/plsqlwebserviceSoapHttpPort
3.) Create a bpel synchronous project with a partnerlink originally pointing to my testing application server WSDL file. Also, I've created a Location property for that same partnerlink with 2 sets of values - first having the ending point of my testing application server and the second one is the ending point of my local OC4J instance.
4.) Deploy the deploy Bpel project to my testing application server.
5.) To test it, I purposely disabled the web service created in step 2 and initiate the Bpel project on the Bpel console. I was hoping that because the primary web service is not available and it will try to call the second one which I've defined in the Location property but it did not work.
Have I misunderstood the concept or missed out some important tasks? Thank you for your timne and assistance.
Have a nice day,
JohnHi Jayakrishna,
In General , there are non execptions in BAPIs, because of the reason, that the exception raised in a SAP envoronment may not mean anything for a non SAP initiator. All the exception situations would only fill the return table(TYpe BAPIRET2 or something like that). If you read that table after the call to the bapi, you can understand what has gone wrong.
Regards,
Ravi -
Exception handling in IDOC using workflows
exeception handling in idoc using workflows
i. what will be the trigerring event in case of idoc ?
ii.will it be BOR -- IDOC<message_type >?
thanks in advance
naval bhattHi Naval Bhatt,
it depends on what you would like to do, but there is an object IDOCAPPL, more information you find Objekttyp IDOC<MSGTYP>:
http://help.sap.com/saphelp_47x200/helpdata/en/04/92725546f311d189470000e829fbbd/frameset.htm
General how it works:
Objects, Events and Tasks to be Created
http://help.sap.com/saphelp_47x200/helpdata/en/78/2176d251ce11d189570000e829fbbd/frameset.htm
This is an example how the application should implement the exception handling in IDOC by using workflows.
Events for example:
- inputErrorOccurred
- inputFinished
Regards
Tibor -
Exception Handling in the OBI EE 10.1.3.4
Hi All,
Is it possible to implement the exception handling in the OBI EE 10.1.3.4
For Ex: Instead of displaying the below error, is it possible to display it in the meaningful way
[nQSError: 10058] A general error has occurred. [nQSError: 27002] Near : Syntax error [nQSError: 26012] . (HY000)
SQL Issued: SELECT SALES_FACT.SALES_AMOUNT, TIMESTAMPDIFF(SQL_TSI_DAY, TIMESTAMP ‘1900-01-01 12:00:00’, TIMESTAMP ‘1900-01-01 12:00:00’), TIME_DIM.BUSINESS_DATE FROM SALES
Thanks in Advance
SivaHi Deepak,
Thank you for responding to the query that i have raised.
As you mentioned that ORA: errors will help in diagnosing the issue.
Do you mean that it will help in diagnosing the issue at the BMM larey & Physical layer join conditions.
Thanks in Advance
Siva -
Bounded Taskflow Exception Handler not working with Page Fragements
I have one bounded - taskflow task-flow-definition
<?xml version="1.0" encoding="windows-1252" ?>
<adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">
<task-flow-definition id="task-flow-definition">
<default-activity>view1</default-activity>
<managed-bean>
<managed-bean-name>backing_main</managed-bean-name>
<managed-bean-class>view.backing.Main</managed-bean-class>
<managed-bean-scope>pageFlow</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>backing_view1</managed-bean-name>
<managed-bean-class>view.backing.View1</managed-bean-class>
<managed-bean-scope>pageFlow</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>backing_view2</managed-bean-name>
<managed-bean-class>view.backing.View2</managed-bean-class>
<managed-bean-scope>pageFlow</managed-bean-scope>
</managed-bean>
<exception-handler>view2</exception-handler>
<view id="view1">
<page>/view1.jsff</page>
</view>
<view id="view2">
<page>/view2.jsff</page>
</view>
<use-page-fragments/>
</task-flow-definition>
</adfc-config>view1.jsff contains one command button, which calls one ActionListener
<?xml version='1.0' encoding='windows-1252'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
<af:commandButton text="commandButton 1" actionListener="#{pageFlowScope.backing_view1.callMyFunction}"
binding="#{pageFlowScope.backing_view1.commandButton1}"
id="commandButton1"/>
<!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_view1-->
</jsp:root>view1.java callMyFunction throws an Exception
public void callMyFunction(ActionEvent event) throws Exception{
throw new Exception();
}view2.jsff is an exception handler
<?xml version='1.0' encoding='windows-1252'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
<af:activeOutputText value="Exception Occured"
binding="#{pageFlowScope.backing_view2.activeOutputText1}"
id="activeOutputText1"
inlineStyle="font-size:xx-large; color:red;"/>
<!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_view2-->
</jsp:root>above taskflow is dragged-drop as a Region in one file main.jspx
<?xml version='1.0' encoding='windows-1252'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
<jsp:directive.page contentType="text/html;charset=windows-1252"/>
<f:view>
<af:document binding="#{pageFlowScope.backing_main.document1}"
id="document1">
<af:form binding="#{pageFlowScope.backing_main.form1}" id="form1">
<af:region value="#{bindings.taskflowdefinition1.regionModel}"
id="taskf1"
binding="#{pageFlowScope.backing_main.taskf1}"/>
</af:form>
</af:document>
</f:view>
<!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_main-->
</jsp:root>*pressing a commandButton on view1.jsff throws an Exception as expected but does not go to exceptionHandler [view2.jsff]*
However, this does work with Bounded Task-Flow without page fragments , view1.jspx contains one button, calling one method which throws an Exception,
view2.jspx is an Exception Handler, and in this case it redirects to the view2.jspx [error page]
any ideas?
thanksHi,
Pretty much. However, you got the event part wrong, which is mostly my fault here. First, let put down some general JSF facts about event handling.
1. http://java.sun.com/javaee/5/docs/api/javax/faces/component/UIComponent.html#queueEvent(javax.faces.event.FacesEvent)
2. So, basically, queuing an event on a component means queuing it on its parent until you reach the UIViewRoot that will really actually queue it. That strategy allows iterating components to intercept event queued on their children to record the row index as well so that the data model can be synchronized correctly during the broadcast phase (see http://java.sun.com/javaee/5/docs/api/javax/faces/component/UIData.html#queueEvent(javax.faces.event.FacesEvent) and http://java.sun.com/javaee/5/docs/api/javax/faces/component/UIData.html#broadcast(javax.faces.event.FacesEvent))
3. Exceptions that aren't handled by the exception handler are thrown during broadcast or various process* methods.
So, the catch component must leverage these facts to intercept events queued on its children (by overriding queueEvent method) wrapping the original event in a custom on that flag the catch component itself as the source of the event. The result will be that the broadcast method of the catch component will be called to handle the event. The broadcast method must then unwrap the event (to get the original event), gets the original source, then call originalSource.broadcast(originalEvent) within a try-catch block.
Does it make any more sense put that way? Note that it's an obscure part of JSF so I cannot make it incredibly simple either.
Regards,
~ Simon -
Custom code as an exception handler not working.
Hi,
I worked on Custom Handler for unauthorized access to a taskflow following the link below and it worked. But a special case in this doesn't work.
http://download.oracle.com/docs/cd/E14571_01/web.1111/b31974/taskflows_complex.htm#ADFFD22602
Scenario-1: I have a link that opens an unauthorized taskflow as blank page. I tried the solution of custom handler and am able to display message or display error page --- WORKS FINE
Scenario-2: I have a link that opens an unauthorized taskflow in a pop-up as blank page. The above solution doesn't work. I tried displaying SOPs but nothing gets print --- DOESN'T WORK.
Details:
The custom handler doesn't work with Pop-ups. I have an unauthorized taskflow that gets called inside a pop-up using a link. Being an unauthorized user, I click on the link and it pops-up with a blank page. As per the custom handler it is supposed to display error-page. But it doesn't.
I tried displaying SOPs inside the handleException method and nothing prints. The exception handler is unable to catch the exception. If this use-case throws some exception, my exception handler would have handle it but it doesn't raise any exception.
Is this something issue that I need to discuss with FMW team?
Any workaround for this would be of great help.
Code Sample:
public void handleException(FacesContext facesContext, Throwable throwable,
PhaseId phaseId) throws Throwable {
String errorMessage = throwable.getMessage();
if (errorMessage != null && errorMessage.indexOf("ADFC-0619") > -1) {
setEL("#{sessionScope.errorMessage}",
"You are not authorized to view this page.");
ExternalContext externalContext =
facesContext.getExternalContext();
externalContext.redirect("ErrorPage");
} else {
super.handleException(facesContext, throwable, phaseId);
Thanks
RazaHi Frank,
This scenario is not specific to a particular TaskFlow. In General, there are links in some views, that invokes taskflows and a particular user may not have permission to that TaskFlow. In this scenario, I am not sure where I need to define the method or router. And Hence I registered the Custom Exception Handler as a service as per the documentation.
But the logic in documentation doesn't work with Pop-ups.
Thanks
Raza -
Generalised Event Exception Handler
Hi all experts,
Can anybody plz tell how to create a generalised Exception Handler , so that wenever a exception is generated in the main method the Exception Event Handler shud be initialised to catch the exception for all the exceptions generated at runtime.
I want the Exception Event Handler to catch the exceptions for RFC BAPI,EJB Webservice,etc..as i am using this in my application to give general message at runtime if any exceptions is generated from the try-catch block.
Waiting for the reply.
Regards:
SKHi SK,
There is a general Exception that you can use for all exceptions thrown.
just add this code for any exception you want to catch.
try
// try anything
catch(Exception e)
// catch any exception
Regards,
Marshall. -
Recommended Practice for Exception handling in JSP portlets
Hi,
This may be a redundant question, but hope to get some feedback on the generally used practice of catching exceptions in a JSP based Portal application.
Is it okay to just make use of the standard JSP errorpage directive in each of the JSP portlets to point to the same errorpage.jsp. If a problem occurs in any of the portlets, the userfriendly message in the errorpage.jsp would be rendered.
Of course there could be some kind of error logging done in the errorpage.jsp to track the error stack. This also means, that you would not want to catch any exceptions inside each of the portlet JSPs but rather let the errorpage directive, be the catch all?
regards
-AnanthMohana,
Pls ignore the voice mail,it was for something else and I was able to talk to Peter as well about this.
Regarding the error/exception handling -
If the errorPage.jsp is used in each of the JSP portlets with the help of the JPS errorPage directive, if a general system failure or major appln. error occurs, you will get the errorPage.jsp containing the user friendly message to show up in each of the half a dozen portlets on the page!!. Is that allright.
You cannot really redirect the entire page using the code inside the JSP portlet. It will only render inside the same portlet. The only way you can do this is to use Javascript.
-Ananth
Maybe you are looking for
-
Another question: Upon creation of a billing doc and with regards to the creation of pricing procedure, this error occurs: Tax statement item missing for tax code S5 (tax code S5 is a deferred output tax) Message no. FF805 Diagnosis No tax item exist
-
File Adapter Writting and Reading strategy
Hi All, When i am trying to write data to file, it was opened by another person and it gave error in the receiver communication channel saying like source is using by another application. Which is well and good But in case of Sender channel while wri
-
How to correct COOKIE + FORCED HTTP METHOD error
I am running a few pages against the Access Me plug-in in firefox and received 3 errors..and 2 warnings... where do i began to resolve these issues? Access Me String Test Results FORCED HTTP METHOD Attack Details: a.. HTTP Method: SECCOMP The attacke
-
Any way to check how many text messages remaining?
Hey guys, Wasnt really sure where to post this, but is there any number or website I can go to check how many text messages I have left in the month for my plan? Thanks
-
Using a Textfield in a similar fashion as an address bar
i am unable to find the property which i should set so as to retain the data entered into the TextField(using JTextField), in order to make out of it a structure similar to an address bar. any idea how to do that?