Exception handling in sorting arrays
Hi all, I have a problem with the use of the built in java sort fo arrays. My program works on an array with 4 or 5 entities. When I run it in some folders it works but not in others. I get the following error after compilation, where "ResultData" is the class of array to be sorted:Exception in thread "main" java.lang.NullPointerException
at ResultData.compareTo(TextEdit.java:1215)
at java.util.Arrays.mergeSort(Arrays.java:1064)
at java.util.Arrays.mergeSort(Arrays.java:1071)
at java.util.Arrays.mergeSort(Arrays.java:1072)
at java.util.Arrays.mergeSort(Arrays.java:1071)
at java.util.Arrays.mergeSort(Arrays.java:1071)
at java.util.Arrays.mergeSort(Arrays.java:1071)
at java.util.Arrays.sort(Arrays.java:1014)
at java.util.Collections.sort(Collections.java:78)
[\code]Can any one give a suggestion?
Here is the code for the class "ResultData"class ResultData implements Comparable
String file1;
String file2;
double var, var1, var2;
public ResultData(String f1,String f2,double v, double x, double y)
file1= f1; file2=f2;
var=v; var1=x; var2=y;
public String getFile1Name()
return file1;
public String getFile2Name()
return file2;
public double getVar()
return var;
public double getVar1()
return var1;
public double getVar2()
return var2;
public String toString()
return file1+" "+file2+" "+var+" "+var1+" "+var2;
public int compareTo(Object o)
ResultData r= (ResultData)o;
double result = this.getVar()- r.getVar();
if (result < 0.0) return -1;
else if(result > 0.0) return 1;
else return 0;
} // ends class ResultData
Similar Messages
-
Exception Handling for Array Binding
Hi
1)
I am using a Stored Procedure.
I am using array binding and if i am sending an array of count 10 to be inserted in a table and only 9 got inserted,i deliberatly inserted one errorneous record in array, the count returned by ExecuteNonQuery() is 10.Why ?
How can i come to know exact number of rows inserted in table, how can i use Output variables, because the array bind count is 10 so if i add an output parameter it gives error ArrayBind count is wrong....
2)
Is it possible to roll back all the inserts if error occurs in any of the insert by Oracle engine.What it does is it inserts all correct records and leaves the errorneous record and doesn't even throw any exception or any message.
Answer - This can be achieved by using OracleTransaction and don't use Exception handling in procedure otherwise there wont be any exception thrown by procedure which is necessary to detect if an error occured during insert.If you use exception handling OracleEngine will insert correct rows and leave errorneous record and return count of inserted + non inserted records which is wrong.
Please help.
Message was edited by:
user556446
Message was edited by:
user556446You'll need to encapsulate your validation within it's own block as described below:
-- this will die on the first exception
declare
TYPE T_BADDATA_TEST IS TABLE OF VARCHAR2(1000) INDEX BY binary_integer ;
tbt T_BADDATA_TEST ;
aBadTypeFound exception ;
begin
tbt(0) := 'a';
tbt(1) := 'b';
tbt(2) := 'c';
for idx in tbt.first..tbt.last loop
if tbt(idx) = 'b' then
raise aBadTypeFound ;
else
dbms_output.put_line(tbt(idx));
end if ;
end loop ;
end ;--encapsulate the exception area in a begin/end block to handle the exception but continue on
declare
TYPE T_BADDATA_TEST IS TABLE OF VARCHAR2(1000) INDEX BY binary_integer ;
tbt T_BADDATA_TEST ;
aBadTypeFound exception ;
begin
tbt(0) := 'a';
tbt(1) := 'b';
tbt(2) := 'c';
for idx in tbt.first..tbt.last loop
BEGIN
if tbt(idx) = 'b' then
raise aBadTypeFound ;
else
dbms_output.put_line(tbt(idx));
end if ;
EXCEPTION
WHEN aBadTypeFound THEN
dbms_output.put_line(tbt(idx) || ' is bad data');
WHEN OTHERS THEN
dbms_output.put_line('exception');
END ;
end loop ;
end ;
output:
a
b is bad data
c
***/ -
Good exception handling policy for Java web application
I'm looking for a good exception handling policy for Java web application. First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace();
Then I found this Oracle page The Message-Driven Bean Class - The Java EE 6 Tutorial, which does just that. So now I'm confused. Is there a good page online for an exception handling policy for Java EE Web applications? I have a hard time finding one. I've read that you should not catch the Exception class. I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop. We have a loop which runs once a minute implemented using the Quartz framework. Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.I'm looking for a good exception handling policy for Java web application.
If you have not done so I suggest you start by reviewing the several trails in The Java Tutorials.
Those trails cover both HOW to use exceptions and WHEN to use them.
This trail discusses the 'controversy' you mention regarding 'Unchecked Exceptions'
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Unchecked Exceptions — The Controversy
Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.
Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Generally don't catch an exception unless you plan to HANDLE the exception. Logging, by itself is NOT handliing.
First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace();
That article, like many, has some good advice and some poor or even bad advice. You get what you pay for!
I've read that you should not catch the Exception class.
Ok - but all that does is indicate that a problem of some sort happened somewhere. Not very useful info. Java goes to a lot of trouble to provide specific exceptions for specific problems.
I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop.
If the exception is 'unknown' then maybe it NEEDS to 'stop all other customers from executing later on in the loop'.
That is EXACTLY why you don't want to do that. You need to identify which exceptions should NOT stop processing and which ones should.
Some 'unknown' exceptions can NOT be recovered and indicate a serious problem, perhaps with the JVM itself. You can NOT just blindly keep executing and ignore them without risking data corruption and/or the integrity of the entire system Java is running on.
Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.
No - not if you want a well-behaved system.
Don't catch exceptions unless you HANDLE/resolve them. There are times when it makes sense to log the exception (which does NOT handle it) and then raise it again so that it gets handled properly later. Yes - I know that is contrary to the advice given in that article but, IMHO, that article is wrong about that point.
If you have ever had to maintain/fix/support someone else's Java code you should already understand how difficult it can be to find WHERE a problem occurs and WHAT the exact problem is when exceptions are not handled properly. -
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 framework?
Can anyone recommend an exception handling framework or perhaps pattern for Applets?
Thanks, Tom.Methinks you're gonna be stuck. Unless every catch block already happens to call some central method (or small set of methods) and passes in the exception, there is no way I can think of to "flip a switch" and magically have all your catch blocks start logging messages when they weren't before. You'll probably have to change the code every place you want to log something. This is why it's a great idea to think of those sorts of things before coding a huge application. :-) I'm not criticizing you since it sounds like you inherited this.
-
Exception handling in jinitiator
hallo,
we are currently using jinitiator 1.3.1.9 and i have a little question concerning the exception handling in it. i don't think, that the handling differes to older version, so maybe one can help me out though he uses an "older" version.
now the problem. we use java functionality either in webmode (jinitiator) and in client-server-mode (wrapper pl/sql unit) and want to pass the java exception trace to the forms, so that we can handle errors in user interaction. we found a way to da that by developing a printstream, which collects trace information in a string. this method works well in client-server-mode but not in webmode. in the first case all the normal trace information is written with the printstream-method println(String). in the webmode case, a different method is used, println(char[]). the strange thing about it is, that the character array contains address information for an object (maybe the string). i my opinion the behaviour is because of the jinitiator. does anyone know about the exception handling and collecting the trace information in jinitiator?? thanks very much in advance.
regards
steffen silberbachhi again,
thanks for answering, but I think you got me wrong or I didn't make myself clearly. I don't want to pass a PL/SQL error to the bean to have it printed out on the console. I want it the other wa around. my problem was to get the stack trace of a java exception and make it accessible to the form to print it out as a message for instance. unfortunately this way is quite impossible to do, because jinitiator has a different exception handling to the sun VM. the jinitiator implements the printStackTrace(*) methods as native calls and obviously the underlying code handles the addresses of the passed trace objects and prints them out the a special console somehow. so if one overwrites the printStack() methods in his own Exception, he gets a problem because of the different exception trace handling in jinitiator. -
Exception handling in stored process, loop IF..ELSE
Hello Guys,
we want to put in exception handling in the loop but get the following error:
Error(43,3): PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: begin case declare end exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimited-identifier> <a bind variable> << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe
create or replace
PROCEDURE xxxx
FOR MESSSY IN
select I.*
FROM x I
LOOP
IF upper(CODE)='N' THEN
INSERT INTO T_MESS(MP)
select I.MP_ID
FROM T_ME
ELSIF upper(MESSSY.k2)='L' THEN
DELETE T_MESS WHERE T_MESS.MP = MESSSY.MP;
END IF;
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
A program attempted to insert duplicate values in a column that is constrained by a unique index.
DBMS_OUTPUT.PUT_LINE ('A program attempted to insert duplicate values in a column that is constrained by a unique index.')
--No Rollback
END;
COMMIT;
END LOOP;
END xxxx;
does someone know why?BluShadow wrote:
Well, your code is missing all sorts of bits and we don't have your data or your exact logic to know what it's supposed to be achieving.
That is right, you dont have my data and that is why I was suprised by your comment.
Since the input table might contain a few thousand rows and each of those might need to
be considered N , D, or C and each case has a different handling I can not imagine how this
can be all done with a merge statement.
MERGE
T_METRICPOINT_META with T_METRICSSYSTEM_LOAD where T_METRICSSYSTEM_LOAD .LOAD_DATE=to_char(sysdate)
WHEN MATCHED THEN --we know those are the metric points that have to be loaded today, but we still need to do a IF..ELSE to handle them
WHEN NOT MATCHED THEN -- not considered in todays load
----original code-----
create or replace
PROCEDURE myprocedure AS
BEGIN
--Extracting the records from T_METRICSSYSTEM_LOAD which have todays load date. Corresponding to these MP_System, we extract the MP_IDs from the T_METRICPOINT_META table.
--Comapring these MP_IDs with the MP_IDs from the source(T_METRICPOINT_IMPORT) and extracting only those Metric points which need to be loaded today.
FOR METRICSSYSTEM IN
select I.*
FROM T_METRICPOINT_IMPORT I
where I.LOADDATE = TO_CHAR(SYSDATE) AND I.MP_ID IN
(select a.MP_ID
from T_METRICPOINT_META a INNER JOIN T_METRICSSYSTEM_LOAD b on a.MP_SYSTEM = b.MP_SYSTEM where b.LOAD_DATE=to_char(sysdate))
LOOP
--If mutation code in the source/import data is "N", the record is inserted as it is in the "T_METRICPOINTS" table.
IF upper(METRICSSYSTEM.MUTATIONCODE)='N' THEN --new
INSERT INTO T_METRICPOINTS(MP_ID, ......)
SELECT DISTINCT I.MP_ID,.....
FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='D' THEN --delete
DELETE T_METRICPOINTS WHERE T_METRICPOINTS.MP_ID = METRICSSYSTEM.MP_ID AND T_METRICPOINTS.KEY = METRICSSYSTEM.KEY;
ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='C' THEN --correction
UPDATE T_HISTORYMETRICPOINTS H
SET CHANGE_DATE = to_char(sysdate)
WHERE H.MP_ID=METRICSSYSTEM.MP_ID AND H.KEY = METRICSSYSTEM.KEY;
INSERT INTO T_HISTORYMETRICPOINTS(MP_ID, KEY, .....)
--The distinct here is used, to handle 2 identical records in the input table with correction value "C". This would insert into 1 record in the T_HISTORYMETRICPOINTS table without
--violating the primary key constraint.
select DISTINCT I.MP_ID,I.KEY, ....
FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
--END IF;
END IF;
COMMIT;
END LOOP;
END myprocedure; -
FORALL Exception handling problem
Hi All,
I have one doubt in forall exception handling. I have gone through the SAVE EXCEPTION for bulk collect but i have one more query
BEGIN
FORALL j IN l_tab.first .. l_tab.last
INSERT INTO exception_test
VALUES (l_tab(i));
EXCEPTION
END;
My requirement is when an exception occurs, i ant to print the values of the collection.
e.g. say l_tab (j).emp_number, l_tab (j).emp_id.
How is that possible?
Thanks
Samarth
Edited by: 950810 on Mar 12, 2013 7:28 PM>
I have one doubt in forall exception handling. I have gone through the SAVE EXCEPTION for bulk collect but i have one more query
BEGIN
FORALL j IN l_tab.first .. l_tab.last
INSERT INTO exception_test
VALUES (l_tab(i));
EXCEPTION
END;
My requirement is when an exception occurs, i ant to print the values of the collection.
e.g. say l_tab (j).emp_number, l_tab (j).emp_id.
How is that possible?
>
Post the code you are using. You didn't post the FORALL that is using SAVE EXCEPTIONS.
The SQL%BULK_EXCEPTIONS associative array that you get has the INDEX of the collection element that caused the exception.
So you need to use those indexes to index into the original collection to get whatever values are in it.
One index from the exception array is:
SQL%BULK_EXCEPTIONS(i).error_index So if your original collection is named 'myCollection' you would reference that collection value as:
myCollection(SQL%BULK_EXCEPTIONS(i).error_index); See 'Handling FORALL Exceptions (%BULK_EXCEPTIONS Attribute)' in the PL/SQL Language doc
http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/tuning.htm#i49099
>
All exceptions raised during the execution are saved in the cursor attribute %BULK_EXCEPTIONS, which stores a collection of records. Each record has two fields:
%BULK_EXCEPTIONS(i).ERROR_INDEX holds the iteration of the FORALL statement during which the exception was raised.
%BULK_EXCEPTIONS(i).ERROR_CODE holds the corresponding Oracle Database error code.
The values stored by %BULK_EXCEPTIONS always refer to the most recently executed FORALL statement. The number of exceptions is saved in %BULK_EXCEPTIONS.COUNT. Its subscripts range from 1 to COUNT.
The individual error messages, or any substitution arguments, are not saved, but the error message text can looked up using ERROR_CODE with SQLERRM as shown in Example 12-9.
You might need to work backward to determine which collection element was used in the iteration that caused an exception. For example, if you use the INDICES OF clause to process a sparse collection, you must step through the elements one by one to find the one corresponding to %BULK_EXCEPTIONS(i).ERROR_INDEX. If you use the VALUES OF clause to process a subset of elements, you must find the element in the index collection whose subscript matches %BULK_EXCEPTIONS(i).ERROR_INDEX, and then use that element's value as the subscript to find the erroneous element in the original collection. -
Exception Handling for errors caused by Remote tables
Hello
I am trying to run a process that retrieves data from a remote table. Unfortunately occasionally the process fails because I exceed the number of simultaneous sessions allowed for the relevant table. I want to be able to handle this by directing the user to an errors page that I have built.
Unfortunately I cannot seem to be able to handle the exception. I have included an EXCEPTION WHEN OTHERS section but this does not seem to work.
Is it possible to handle these sort of errors? If it is possible I want to transfer this process into an asynchronous process so that the query can run in the background.
Cheers IanThe code within my PLSQL DBMS JOB process is;
declare
CURSOR curTest IS
SELECT DISTINCT PREMISE_ID FROM RWN_OOA_IMPORT WHERE PREMISE_ID IS NOT NULL;
recTest curTest%ROWTYPE;
l_value NUMBER :=1;
l_process NUMBER;
begin
l_process := GET_CURRENT_PROCESS(1030);
UPDATE IMPORT_PROCESS SET VOLUME_EXPECTED = (SELECT COUNT(PREMISE_ID) FROM (SELECT DISTINCT PREMISE_ID FROM RWN_OOA_IMPORT WHERE PREMISE_ID IS NOT NULL), PROCESS_STARTED = 1 WHERE PROCESS_ORDER = l_process;
commit;
FOR recTest IN curTest
LOOP
INSERT INTO CD_IMPORT (PREMISE_ID, LINK_REF, AT_CODE, TABLE_ID)
(SELECT PRO_NUMBER, LINK_REFERENCE, CD_CPA.AT_CODE, 1 FROM CD_CPA
WHERE PRO_NUMBER = rectest.PREMISE_ID AND ACCOUNT_NAME IS NOT NULL);
UPDATE_STATUS(l_process, l_value);
l_value := l_value + 1;
END LOOP;
EXCEPTION
WHEN err_type.REMOTE_OBJECT_FAILURE THEN
UPDATE_PROCESS_ERROR(DBMS_UTILITY.FORMAT_ERROR_STACK,l_process);
WHEN err_type.RECURSIVE_SQL_LEVEL THEN
UPDATE_PROCESS_ERROR(DBMS_UTILITY.FORMAT_ERROR_STACK,l_process);
WHEN err_type.SIMULTANEOUS_SESSIONS THEN
UPDATE_PROCESS_ERROR(DBMS_UTILITY.FORMAT_ERROR_STACK,l_process);
WHEN err_type.PRECEDING_ERROR THEN
UPDATE_PROCESS_ERROR(DBMS_UTILITY.FORMAT_ERROR_STACK,l_process);
WHEN OTHERS THEN
UPDATE_PROCESS_ERROR('Unhandled Error message' ,l_process);
end;
The table CD_CPA is the synonym to the DBlink table. The other processes used in this process is the UPDATE_PROCESS_ERROR shown below;
create or replace procedure "UPDATE_PROCESS_ERROR"
(in_error IN VARCHAR2, in_process_id IN NUMBER)
is
begin
EXECUTE IMMEDIATE 'UPDATE IMPORT_PROCESS SET ERROR_MESSAGE = ' || chr(39) || in_error || chr(39) || ', ERROR = 1 WHERE PROCESS_ORDER = ' || in_process_id;
commit;
end;
There is also the package err_type which holds the 4 error messages I get when I run or compile this process;
create or replace PACKAGE err_type
IS
REMOTE_OBJECT_FAILURE EXCEPTION;
PRAGMA EXCEPTION_INIT(REMOTE_OBJECT_FAILURE,-4052);
RECURSIVE_SQL_LEVEL EXCEPTION;
PRAGMA EXCEPTION_INIT(RECURSIVE_SQL_LEVEL,-604);
SIMULTANEOUS_SESSIONS EXCEPTION;
PRAGMA EXCEPTION_INIT(SIMULTANEOUS_SESSIONS,-2391);
PRECEDING_ERROR EXCEPTION;
PRAGMA EXCEPTION_INIT(PRECEDING_ERROR,-2063);
end err_type;
Hope this helps. -
Exception Handling for inserts
Hi,
My requirement is to populate a table with values got by selecting columns from various table on join conditions. It works fine if all the rows inserted are unique. However if the row to be inserted is duplicate, it violates the uniqueness constraint.
I want an exception wherein if select query returns 100 rows, of which 80 are already there in the table to be populated, it should just insert the 20 records.
Below is the SP i wrote for the same. However, as soon as it meets exception condition, it just prints the condition and exits, without processing the rest of the records. Please look at the SP below and suggest a solution.
create or replace
PROCEDURE PP_CMC_TEST AS
cursor c1 is
(select cdu.subscription_id,max(cdu.account_id),max(s.subscription_versn_start_date),
max(s.service_plan_id),max(sbp.billing_period_id),sysdate-1
,cdu.device_name, cdu.resource_id,sum(cdu.usage),max(cdu.unit_of_measurement)
from
subscriptions s, subscription_billing_period sbp, consolidated_daily_usage cdu
where s.version_end_date is null and
sysdate-1 between sbp.start_date and sbp.end_date and
cdu.usage_date between sbp.start_date and sbp.end_date
and s.subscription_id = cdu.subscription_id
and sbp.subscription_id = cdu.subscription_id
and sbp.subscription_id = s.subscription_id
and s.subscription_versn_start_date=sbp.subscription_versn_start_date
group by cdu.subscription_id,cdu.device_name, cdu.resource_id);
a number;
b number;
c date;
d number;
e number;
f date;
g varchar2 (255);
h number;
i number;
j varchar2(60);
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO a,b,c,d,e,f,g,h,i,j;
EXIT WHEN c1%NOTFOUND;
insert into cmc_test
(subscription_id,account_id,subscription_versn_start_date,service_plan_id,billing_period_id,curr_date,
device_name,resource_id,usage,unit_of_measurement) values
(a,b,c,d,e,f,g,h,i,j);
END LOOP;
EXCEPTION
WHEN DUP_VAL_ON_INDEX
THEN
DBMS_OUTPUT.PUT_LINE('DUPLICATE RECORD FOUND');
commit;
CLOSE c1;
END PP_CMC_TEST;Edited by: BluShadow on 07-Feb-2012 09:03
added {noformat}{noformat} tags (for what it was worth). Please read {message:id=9360002} and learn to do this yourself in future.Using SQL you would create an error table and modify the INSERT to log the errors. See the 'Inserting Into a Table with Error Logging' section of http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_9014.htm. Note this approach will not work if you are using direct path loads since the log table won't be used.
If you are going to use PL/SQL for this then what you want is to use BULK COLLECT and then a FORALL with a SAVE EXCEPTIONS clause.
>
A. BULK COLLECT INTO plsqlTable LIMIT 5000 - These are your new records you want to INSERT
B. FORALL ... SAVE EXCEPTIONS - This is the INSERT query to insert the new records
C. Use a bulk exception handler. Any record in the FORALL that causes an exception will have it's index put into the bulk exception array. In the bulk exception handler you can loop through the array and access the records that caused the error using the index into the plsqlTable and do any error logging you need to do.
>
The bulk exception array will have the plsql table index of the row that caused the error. You can index into the plsql table (see Step A above) to access the record and then log it, INSERT it into a duplicates table or whatever you want.
The important thing is that the records that do not have errors will still get processed. Similar result to what will happen if you use SQL and an error table. -
TaskFlow Exception Handler Behavior
Hi all,
I have a question about taskflow exception handler.
My customer is using method-call exception handler to display error detail as FacesMessage dialog in their taskflow.
And they are now trying to find the way to call exception handler but not to show the dialog in case that some sort of exceptions happen.
To achieve this requirement they delete FacesContext.addMesage() from their exception handler, but when not call addMessage() they always get return code 500 (internal server error).
From the behavior we've got, do we always need to call addMessage() in it to come back to original page?
Regards,
AtsushiHi Frank,
Thank you for your reply. Please let me ask you another question.
When method-call error handler is executed it returns an outcome. And the outcome determines the next activity I get to.
My question is whether it is a designed behavior of method-call error handler that when the below two conditions are met I get back to the original error page to see facesMessage dialog.
1. The method-call outcome doesn't match any control flow case
2. addMessage() is called in the method defined at method-call
If any, I'd like to know how to get back the original page after error handler is executed without faces message.
Thanks,
Atsushi -
Utl_file - exception handling when inserted in bulk.
Hi,
I am using Oracle 10gR2. I wanted to write data to a file. Due to huge number of records, I am collecting them into a collection, traversing e collection, appending the values in collection to a varchar variable with new line in a loop.If the array size is say 50, I will have 50 values in the Vatchar variable separated by CHR(10). and I will insert the variable using UTL_FILE.PUT so that 50 lines will be inserted with values into the file.
Now my query is if any one among those 50 values gives an exception, I feel all the 50 values can't be loaded. Please suggest exception handling in this case.
Regards,
Naveen Kumar.C.
Edited by: Naveen Kumar C on Sep 17, 2009 5:23 PMYou could use a CLOB in conjunction with UTL_FILE to write it out 32K at a time...
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 l_file UTL_FILE.FILE_TYPE;
3 l_clob CLOB;
4 l_buffer VARCHAR2(32767);
5 l_amount BINARY_INTEGER := 32767;
6 l_pos INTEGER := 1;
7 BEGIN
8 BEGIN
9 SELECT dbms_xmlgen.getxmltype('select * from emp natural join dept').getclobval()
10 INTO l_clob
11 FROM dual;
12 EXCEPTION
13 WHEN NO_DATA_FOUND THEN
14 RETURN;
15 END;
16 l_file := UTL_FILE.fopen('TEST_DIR', 'Sample2.txt', 'w', 32767);
17 LOOP
18 DBMS_LOB.read (l_clob, l_amount, l_pos, l_buffer);
19 UTL_FILE.put(l_file, l_buffer);
20 l_pos := l_pos + l_amount;
21 END LOOP;
22 EXCEPTION
23 WHEN NO_DATA_FOUND THEN -- occurs when end of CLOB reached
24 UTL_FILE.fclose(l_file);
25 WHEN OTHERS THEN
26 DBMS_OUTPUT.put_line(SQLERRM);
27 UTL_FILE.fclose(l_file);
28* END;
SQL> /
PL/SQL procedure successfully completed.
SQL> -
Verifier Error: Exception handlers not sorted in ascending order by the off
Hello,
Java Card 2.2 did not convert my Applet !
Java Card 2.2.1 & 2.1.2 do not report this Error and the Applet is working !
What's wrong here ?
D:\save\smsTest>C:\Programme\Java\jdk1.5.0_06\bin\java -classpath D:\java_card_kit-2_2\lib\converter.jar;D:\java_card_kit-2_2\lib\offcardverifier.jar com.sun.javacard.converter.Converter -config SMS_JCDK_2_2.opt
Java Card 2.2 Class File Converter (version 1.3)
Copyright 2002 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms.
warning: You did not supply export file for the previous minor version of the package
parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\IExceptionConstants.class
parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\ITestConsts.class
parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\InfoData.class
parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\SMS.class
parsing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\StringConsts.class
converting com.gieseckedevrient.jctt.smsTest.IExceptionConstants
converting com.gieseckedevrient.jctt.smsTest.ITestConsts
converting com.gieseckedevrient.jctt.smsTest.InfoData
parsing D:\java_card_kit-2_2\api_export_files\java\lang\javacard\lang.exp
converting com.gieseckedevrient.jctt.smsTest.SMS
parsing D:\java_card_kit-2_2\api_export_files\javacard\framework\javacard\framework.exp
parsing U:\_Tools\java\43019-560\Annex_B_Export_Files\sim\toolkit\javacard\toolkit.exp
converting com.gieseckedevrient.jctt.smsTest.StringConsts
writing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\javacard\smsTest.exp
writing D:\save\smsTest\com\gieseckedevrient\jctt\smsTest\javacard\smsTest.jca
Verifier Error: Exception handlers not sorted in ascending order by the offset of the handler
Verification failedHello again,
it seams this error only occurs when using javac from JDK 1.5/1.6 (1.4 not tested).
When I us jdk1.3.1_11 to compile the java sources this error never occurs during conversion ! -
A catch-all "exception handler" - what's the end of an stack trace?
I've created an application that is beeing tested these days, and I thought it would be a good idea to implement a "catch-all" exception handler so that I could notify the user when an exception occur (so that he may stop, send me the log, and to prevent errors that occur as a result of the first one).
The way I've started implementing it is I redirect error out to a custom output stream:
public class ConsoleOutStream extends ByteArrayOutputStream {
private JFrame owner;
public ConsoleOutStream(JFrame owner) {
this.owner = owner;
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this byte array output stream.
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
public synchronized void write(byte b[], int off, int len) {
super.write(b, off, len);
checkForExceptions();
* Writes the specified byte to this byte array output stream.
* @param b the byte to be written.
public synchronized void write(int b) {
super.write(b);
checkForExceptions();
private void checkForExceptions() {
reset();
if(this.toString().indexOf("xception") != -1) {
System.out.println("Exception!!\n\n");
System.out.println(this.toString());
}then i redirect System.err:
PrintStream out = new PrintStream(new ConsoleOutStream(this));
System.setErr(out);
The problem is that the checkForExceptions() method will be called, e.g. 3 times for each exception - and I just want to display an error message to the user once (of course).
Anyone done something similar?I'm interested in catching all "unhandled errors"how about:
public static void main(String[] args){
try{
//whatever you would normally call from main
}catch (Throwable e){
System.out.println("There was an unhandled exception:");
e.printStackTrace();
} -
MC.9 and MCY1 and Exception Handling in (Logistics Inf. Sys)LIS
Hi,
I want the 'Valuated Stock Value" greater then or equal to zero (>=) appear in the MC.9 report. I can create 'Exception' in MCY1 but am unable to do so. Once I am in MCY1; I choose 'Requirements' then Key Figure 'Valuated Stock Value' then 'Type of condition' is 'Threshold Val. Anal.' is set to '> 0'. However, the report still displays zero values in MC.9. I don't want to display 'Valuated Stock Value' zero to be displayed on the report. Please help.
Thanks
NavedHey Chris,
I got the point for exception handling in weblogic 9.2. We ae using 9.2. It comes up with the concept of shared page flows which means all my unhandled exceptions are thrown to the shared page flow controller. There based on the type of exception, i can forward the request to appropraite page.
Thanks anywyas,
Saurabh
Maybe you are looking for
-
I need to close the tab that is open before it will open a new one from the link.
-
Audio waveform sync and drifting problems on imported AIF's in FCP 6
Hi FCP people, I have been having problems importing bounced audio files into Final Cut Pro 6. I've done a search and can't find anything to help me yet, so here's a new post. This has happened on two projects: both files are 16-bit 48KHz. 1) Having
-
Can I store only my movies in an external drive and still sync them to iPod
I have an 80GB ipod, and as I began ripping a few DVD sets of TV shows onto my computer I realized that I believe I can rip every single DVD I own and store it onto my iPod. I will be on the road constantly over the next year or more and would like t
-
Connecting laptop to internet via cell phone
I heard i can use my cell phone to connect my laptop to the internet, i currently have a lg envy touch , with a 25 megabyte plan which would not be enough as I am wanting to get rid of current dsl plan and wanting to use my wireless plan as my only p
-
MSI Z97-G43 Gaming microphone not working
Hi, I installed my new MSI Z97-G43 today but my microphone doesn't work... It still works on my old computeur... I tried to connect it in front panel too, it doesn't work too... What can i do? BR