JSP newbie - exception handling question
I have created a method in the declarations sections of my jsp. When a particular exception is found (caught inside my method), i want to be able to redirect the output to either another jsp page, or simply print a message on the page in which the exception occurred. I am having some trouble figuring this out. Any advice?
There are many ways to do so.
One way is to define error pages. The details about this is given in the article below
http://java.sun.com/developer/EJTechTips/2003/tt0114.html
Other way is to do something like this :
if ( haveError ) {
out.println( errors.toString());
pageContext.include( "GetName.jsp" );
} else
pageContext.forward( "NextPage.jsp" );
But, I have a suggestion, if possible, do not put method declaration in JSP pages. Its not a good practice. Put all the code in beans. JSP should only contain display stuff.
Vaibhav
Similar Messages
-
Exception Handling for many bean objects of a container class in a JSP page
Hello,
I have on container bean class. In this container class, there are several others class objects and the getter methods to get these objects out to the JSP pages.
I have one JSP page which will use different objects in the container class object through the getter methods of the container class.
My question is how to implement the exception handler for all the objects in the container so that the JSP page can handle all exceptions if occurrs in any object in the container?
Please give me some suggestions. Thanks
TuThanks for your reply.
Since the container is the accessor class, I have no other super class for this container class, I think I will try the try catch block in the getter methods. -
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 -
This question has been asked time and again, without any clear answers to it. I would appreciate if some one can help me on this.
I am developing a web application with the following architecture:
JSF page calls backing bean methods which calls the service methods. Now my service methods can throw different exceptions like ValidationException, BusinessException, SystemException etc.
Now, what i want to do is : If Validation/Business Exceptions are thrown show the error messages to the user on the same page from which the action was called. And if a SystemException is thrown navigate to a default error page.
How can i handle this thing? Any clues?Thanks for the reply BalusC,
I checked the log files (application log as well as server log) also and there is no other stack trace besides of the exception which i am throwing. Let me elaborate on the exact issue:
I am trying to handle concurrency issues in my application. For example, When two users simultaneously try to edit the same record, the user who first saves the changes successfully. Now when the second user tries to save the changes i want to show him a message that "This record has been modified after you opened it for edit. Please refresh your page and reapply the changes". To show this message i am throwing a BusinessException from my service, which in turn gets propagated to my saveAction method. The saveAction method needs to handle this exception and somehow should show the above message to the user.
To achieve this,
1. i tried catching the exception in my saveAction and added the necessary faces message to FacesContext object. But it does not work. Later i read the reason behind this too, that in the invoke application phase a new context will be created and the messages will not be available to it.
2. I then added the throws clause to my saveAction method, so that my default exception handler will handle it.
saveAction method signature :
public String saveAction () throws BusinessException {
//some code here for save
return null;
}This is my code for the ErrorHandler.jsp:
<body>
<h1 style="color: red">Error</h1><br/><%
// print stack trace.
ExceptionHandler exceptionHandler = new ExceptionHandler();
// unwrap ServletExceptions.
while (exception instanceof ServletException || exception instanceof FacesException ||
exception instanceof ApplicationException) {
if(exception instanceof ServletException) {
exception = ((ServletException) exception).getRootCause();
} else if(exception instanceof FacesException) {
exception = ((FacesException) exception).getCause();
} else if(exception instanceof ApplicationException) {
exception = ((ApplicationException) exception).getCause();
%><font color="red"><%=exceptionHandler.handleException(exception)%></font><br/></body>and this is my code for the handleException method defined in the ExceptionHandler.java:
public static String getMessage(final String msgKey, final Object args[]) {
String message = messages.getProperty(msgKey);
if(args != null) {
final String replaceArgs[] = (String[]) args;
for(int i = 0; i < replaceArgs.length; i++)
message = message.replaceFirst("{" + i + "}", replaceArgs);
return message;
public String handleException(final Throwable exception) {
logger.debug("handleException called..");
String errorMessage = "Unknown error occured.";
String stackTrace = "Stacktrace can not be found. Please check the logs for more details.";
String errorString = null;
final StringWriter stringWriter = new StringWriter();
if(exception != null) {
exception.printStackTrace (new PrintWriter (stringWriter));
stackTrace = stringWriter.toString();
errorMessage = getMessage(exception.getMessage(), null);
errorString = "<b>" + errorMessage + "</b> <br> </br> <br> <input id=\"show\" type=\"button\" value=\"Show Details >>\" onClick=\"toggle();\" /> <div id=\"errorStackTrace\" style=\"display:none;\" > <pre>" + stackTrace + "</pre> </div>";
return errorString;
With the help of this code, i am simply trying to navigate to the error page if an exception occurs and display the appropriate error message with the stacktrace.
The strange thing is, the ErrorHandler.jsp page correctly gets called, which in turn calls the handleException method which returns the formatted error string. (I checked this by adding log statements everywhere). But the system does not actually navigates to the ErrorHandler.jsp page and shows an alert with the following message : "Request error, status : 500 Internal Server Error message : "
Can someone help me figure out what exactly the problem is? -
Jsp newbie having trouble using JSP's with Jdev 10.1.3
Hi,
Have been bashing my head for about two hours with this, if anyone can help will substantially improve my life.
First off apologies if question is stupid or obvious I am a jsp newbie.
Have been experimenting with using the Jsp Taglibrary for tabbed panes in a browser.
http://www.ditchnet.org/tabs/
I have followed all the installation instructions but in JDeveloper when I build I get the message
Error(18,2): method setJspContext(javax.servlet.jsp.PageContext) not found in class org.ditchnet.jsp.taglib.tabs.handler.TabConfigTag
Any idea what jar file I'm missing.
I'm a bit lost, thanksArrrrrrrrgh,
Sorted my problem.
Rebuilt project, works fine now, no idea what was going on (just generally!).
Thanks for input Shay
Mark -
Exception handling within a value-binding expression
Hi all,
Forgive me if this question seems odd, but I am a long-time Struts developer, new to JSF.
In Struts, exception handling was easy because all requests were funnelled through some subclass of Action. Exception handling could effectively be consolidated into one spot by applying the template-method pattern.
Of course, with JSF, this is not possible because method names in value-binding and action-binding expressions can be chosen arbitrarily. For this reason, I am exploring aspect-oriented (and other) techniques for consolidation JSF exception handling into one spot, but rather than focus too intently on that, it's clear that I first need the ability to forward to an error page when an exception is encountered in a value-binding or action-binding expression.
For action-binding expressions, ExternalContext.dispatch("<view id>"); seems to work quite well, but I am unable to make the same work when in the context of a value-binding expression. This is probably attributed to the fact that at that point, I am in an entirely different phase of the JSF request processing lifecycle.
What I'm looking to know is if anyone has a reliable means of forwarding to an error page within the context of a value-binding expression. Better yet, does anyone know a reliable way of forwarding to another view regardless of what phase you are in?
If it makes a difference (and I think it does) the error page uses JSF as well, and uses the same layout (provided via custom tags courtesy of JSP 2.0 tag files), so some view components would have the same name as the page which encountered the error. This seems to get in the way of me simply defining the error page for a 500 in my web deployment descriptor.
Thanks in advance to anyone with a working suggestion.
-KentLet me pose a purely hypothetical use case to demonstrate the problem:
Imagine a page in an HR app, employeeDetails.jsp, that displays an always-up-to-date combo box which lists employee names and IDs. onChange triggers a form submit with the intention of simply posting back to this page, with various text boxes, etc. below updated to show all information for the selected employee.
Obviously, with the requirement that the combo box always be up to date, it's clear that the getter invoked by the value-binding expression must access the database (not directly of course, but via a facade, application, then data-access layer). Any unexpected and unchecked exception in this chain would propagate back up to the getter method on the backing bean. I need to, at that point, log the exception (trivial) and forward to a user-friendly error page.
I suppose I could put some contraint on myself that data access is only performed within ActionEvent handlers, but I'm not sure that's consistent with the JSF model in general, in fact it almost seems Struts-like in that I'd have to invoke some action before loading this form to build the up-to-date list for the combo box, shove it in request scope, where it's then available to the page indicated by the navigation rules. Submission of the form on the page in question would also need to result in rebuilding the up-to-date list. Now we're looking at firther propagation of code. I want to avoid this, so I am looking for a better way. -
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 Processing Question -Reply
I don't use Forte (yet--that's why I joined the mailing list), but since your
question is a generic "engineering practices" question, I'll chime in. I do
use exceptions both in C++ in Delphi, and have developed some opinions
about how to use them:
- Use exceptions for handling "behavior unexpected in the normal course
of your algorithm". In other words, instead of returning error codes
when something goes wrong, throw an exception.
One example of this is in a parser: if you get an illegal token, just throw
an exception.
- When you need to make a choice based on a return status, don't throw
an exception. In the parser example, if you get token 'A', you need to do
one thing and if you get token 'B' you need to do another.
- There's a fine distinction between "handling an error" and "making a
choice", and there are cases where you could argue one way or the
other. I'd say that an error throws an exception when it would normally
terminate the normal flow of execution. For example, "out of memory" or
"illegal token".
- Catch exceptions at "high level" process start/end points, or where it is
required to clean up resources held and rethrow.
- Don't catch exceptions in every single method--it defeats the purpose.
User Interfaces:
- If your user-interface dictates a logical place to unwind no further,
catch exceptions there. For example: In the Windows world most apps
are a window with a menu. If you pull down and pick a menu item to
execute a command, and that command throws an exception, the
exception should be caught, a modal message box indicating the error
should be presented, and then when the user clicks "ok", the program
returns to its normal waiting state with the window intact.
- If you have a modal dialog up, throwing an exception should either stop
at the dialog's event loop or take the dialog down with it.
I'd say that on-screen data validation should NOT use exceptions
because "user typing invalid data" is expected behavior for a UI.
Besides, the UI designer should be smart enough to deal with giving you
a good model for data validation. OTOH, if you take the data out of the
dialog and then pass the information as parameters to a function, and
that function can't handle one of the parameter values, it should throw an
exception.
Nevertheless, if your dialog runs out of memory for some reason, it
should throw an exception and the dialog should come down.
Hope this helps.
-- Conrad Herrmann
Jerry Fatcheric <[email protected]> 07/24/96 03:29am >>>
I have a toss up question for 50 points -
We have finished the first phase of our project and have place
exception processing in the places where we saw exceptions could be
raise. But what about those other exceptional exceptions?
Is this just good programming practice to have a high level generic
exception handler (and what should it really do??) or is it critical.
In addition, when handling data validation on specific widgets on a
screen (e.g. the account number entered must be one of the existing
10,000 valid ones), should this be handled via exception processing or
should it just be handled with code in the event loop?
Any opinions - please I don't want to hear the Forte Party line.
I would like to hear opinions based upon real experience.
Jerry Fatcheric
Relational Options, Inc.
Florham Park, New Jersey
201-301-0200
201-301-00377 (FAX) [email protected]We have finished the first phase of our project and have place
exception processing in the places where we saw exceptions could
be raise. But what about those other exceptional exceptions?
Is this just good programming practice to have a high level
generic exception handler (and what should it really do??) or
is it critical.IMHO, you need to program for these ones that could occur because
if you don't the exception will still happen except without
your normal graceful (or standard) approach manner. I think it is good programming
practice to trap on the ones you think can possible occur if they require
something different in how they react. Otherwise, use of GenericException
with a proper response is called for.
>
In addition, when handling data validation on specific widgets
on a screen (e.g. the account number entered must be one of the
existing 10,000 valid ones), should this be handled via exception
processing or should it just be handled with code in the event loop?
I use event loop processing because most of the time I am also
keeping the user on the same widget after cancelling all events
posted. So, in effect they are back where they started from.
Any opinions - please I don't want to hear the Forte Party line.
I would like to hear opinions based upon real experience.
Jerry Fatcheric
[email protected]@Sagesoln.com
my 2 cents, or should I say my attempt at 50 points, Jerry.
Len Leber
ATG Partners -
Quick question, gurus.... From exception handling perspective, is "no_data_found" inclusive of "others". In other words, if my query returns no data and I use "others" without a "no_data_found" will the exception utilize "others"?
Thanks.
I give points.
I supposed I could have tested this using a quick anon block but didn't think about it just now.
Edited by: sreese on Apr 13, 2012 3:54 PMsreese wrote:
Quick question, gurus.... From exception handling perspective, is "no_data_found" inclusive of "others". In other words, if my query returns no data and I use "others" without a "no_data_found" will the exception utilize "others"?Try it out and let us know, keeping in mind that if your code expects to encounter NO_DATA_FOUND then you need to trap that exception and handle it appropriately. How can you possibly pretend to know how to handle an error that is by it's very definition "unknown" (when others).
sreese wrote:
I give points.
I supposed I could have tested this using a quick anon block but didn't think about it just now.I'd prefer you keep the points and try this out yourself ... much better way to learn. -
Exception Handling In Struts, Declarative, programatic and customized excep
hello .
I'm workingon exception handling in struts , i executed the gobal exceptions.
In glabal exception handling , one will not get the root cause of exception , rather we print the message from resource bundle.
How to get the root cause of exception in jsp page.
Give me sample code to deal with ExceptionHandler claas.
Thank u
RoshuHi ,
I am in the same situation. Global exception is working fine in my struts application . But I need to show the exception stack trace also in the screen whenever the exception occurs.Can anyone please provide me a sample code to deal with ExceptionHandler class ?
Thanks in advance...
Regards,
BG -
Exception Handling-rite way??
Hi Friends,
This Exception handling is really causing some problems for me.I run a query,return the resultset,cook the data from my other java class and display it thru my jsp and the last statement from my jsp is to call the close method(commented out).The problem is if some unknown Exception arises the close() method is not being called,causing open connections which later on are
creating some disasters.I tried to implement it now using the finally method,so that it always gets closed,but hte problem is when i call the ReturnResultSet() method and try to cook the data,it says "ResultSet Closed".Please tell me which is the right way to implement this:
public ResultSet ReturnResultSet(String Query) throws Exception
try{
if (datasource != null) {
connection = datasource.getConnection();
if (connection != null) {
statement = connection.createStatement( );
resultset = statement.executeQuery(Query);
return resultset;
} catch (SQLException sqle)
sqle.printStackTrace();
return null;
finally {
try {
if (resultset != null) resultset.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
catch (SQLException sqle) {
sqle.printStackTrace();
public void close()
try { resultset.close(); } catch (Exception ex) {}
try { statement.close(); } catch (Exception ex) {}
try { connection.close(); } catch (Exception ex) {}
*/Any help would be appreciated and some duke dollars would be awarded too.ThanksOk I think i got your point and i should award you
the duke dollars too,but one last thing to ask.I call
the close() method after all my processing is over,I
just
wanna know should I have the connection.close() thing
inside it,becuase dont that contradicts the whole
connection pool thing,as i am closing a connection
and it has to open a new connection for every
request.Or should i just have resultset.close() and
statement.close() in it.
Thanks for all your helpAre you talking about a standard J2EE container-provided connection pool? If so, then yes, you still need to 'close' the connection. That doesn't actually close it, it just tells the pool it is available to be used again the next time someone asks it for a connection. Hopefully you're not writing your own home-grown "connection pool". -
Exception Handling and Stack Traces in JDK 1.1.8
Hi,
I'm presently maintain and upgrading a Web-Objects 4.5 application that uses the JDK 1.18. There are two constantly recurring exceptions that keep getting thrown, exceptions for which there are no stack traces. These are exceptions thrown by methods that do not presently have throws or try/catch code associated with them.
My questions are:
1) Why are there no stack traces available? Is it because the exception handling code is not there, or could there be another reason?
2) Will the inclusion of exception-handling code ALWAYS lead to stack traces and messages becoming available (if I put a e.printStackTrace() in my catch(Excetion e) clause), or will there be situations where it will not be available?
3) What is the best way for me to handle these types of exceptions in order to gain the most information possible about their root causes and possible solutions?
Thanks for your help.I have never seen a case where there was no stack trace.
I have seen cases where the stack trace does not provide line numbers. I have also seen cases where it is less than useful as it terminates on a native call (which is to be expected.)
However, if you don't call printStackTrace() then you don't get it. And if you catch an exception an throw a different one you also loose information. So you might want to check those possibilities. -
Error/Exception handling in MQSeries
Hi,
What is the robust (yet simple) way to handle any exception generated while doing any operation in MQ Series for e.g. putting messages on queue.
Currently i have just done exception handling using try/catch blocks in my java application.
Kindly explain.
Thanks,
SahilThis forum is specific to the Sun Java System Message Queue
product and is not a forum on IBM's MQSeries product.
If you have a question on MQSeries, you may want to look for a forum on IBM's site. -
Exception Handling Within Methods
I'm currently looking over exception handling within Java and have what whats probably a very simple question to answer!
If within a method I have a try and catch block to handle all exceptions that the specific method may throw, do I then also need to specify the exceptions that the method will throw within its signature? (As I have already handled them).After a bit more reading I think i've found my answer.
You only declare a method throws an exception if you wish to deal with it further up the method call stack. This raises another question though. If I did handle the exceptions that my method could throw within the method itself as well as declaring the method to throw the exceptions within its signature. What would happen? -
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
Maybe you are looking for
-
External Data Refresh failed - Unable to refresh list data in Excel Web Access WebPart
Hi, I have created a PivotChart in Excel workbook that fetches data from a SharePoint list using "OData Data Feed". When refreshing the connection in Excel 2013, the updated data is displayed in PivotChart. But when i upload the same to a SharePoint
-
Is it possible to create a price list which is non-taxable?
Is it possible to create a price list which is non-taxable?
-
Iphone 4s Yellow Tinted Screen
I am going to buy iphone 4s but please tell me the exact answer why people are facing yellow tinted screen problem on iphone 4s? Should i buy it or not?
-
Nokia lumia 920 only showing as a camera on Window...
my lumia 920 is only showing as a camera when connected to my Windows xp, when you open the camera file there are four files inside but you can't downloads any files into them. can someone help me please. has anyone also had this problem
-
CCM automated (batch) upload program to Procurement Catalog
Hello to all, There does not appear to be a report to enable an automated (batch) upload program to a CCM Procurement Catalog. This is a problem for customers who need off-hours periodic updating of their procurement catalog. Has anyone encountered