Exception handling in run()
Hi,
now here is the situation
one of my classes that i made ClassA calls a run method of ClassB
ClassB in its run method calls a local method throwMethod() that throws an exception
now i want this exception to goto ClassA but because run method doesnot say
"Throws Exception" it is giving me some problem.
here is a sample code of what i am trying to accomplish:
public ClassA{
public static void main(){
ClassB b = new ClassB();
try{
b.run();}
catch (Exception ex){
System.out.println("yay Exception caught from classB's methodThrow "); //
}//main of classA
}//classA
publc ClassB implements Runnable{
run() throws exception //this is not valid as the run() in Runnable doesnot
//throw any exceptions.
methodThrow();
}//run of classB
public void methodThrow() thorws Exception{
throws new Exception("Goto classA");
}//methodThrow
}//ClassBthis is what i am trying to do and its not letting me do this..
i just want to ask this if a run method cannot throw any exception how i am supposed to handle exception if i want to handle that exception in the class calling the run of this class... or is it that i can only handle exception inside the run itself (which i cannot as this is not what i want to do..)
OR how can i tell the ClassA (which calls the ClassB.run() ) that the run method didnt execute properly so that ClassA can handle that situation properly like : put a system.out.println("the class didnt run"); or something
i would really appreciate the help...
They are not part of a method signature, but they are
part of the interface's contract, normally shown
using @throws tags in the documentation. The JLS
doesn't cover contracts, only the language. There's
plenty of examples in the standard API where the
interface's contract documents that a specific
runtime exception is thrown under certain
circumstances. But the fact that an unchecked exception is not described in the documentation doesn't mean that an implementing method must not throw it. So throwing any unchecked exception can never break a contract IMO, unless the docs specifically state that the exception must not be thrown, or must only be thrown in certain circumstances.
For example, calling Iterator.next()
after Iterator.hasNext() returns false breaks the
contract of the Iterator interface, and causes a
runtime exception to be thrown, but has no impact on
the method signatures when overriding them. Right. Following up with that, let's say I have an Iterator that is iterating over some sort of stream (reading bytes or lines or something). If the stream is interrupted, it's appropriate to throw an exception even though such behavior is not documented in the Iterator interface, and you would not break a contract to throw an exception.
The contract of
Runnable is that it may be called and not create any
recoverable exceptions, or else it will kill the
calling thread. If there was a good reason for
requiring the client to handle the exception, that
reason won't magically go away if you change it so
the compiler won't complain about it.Right. I had to think about it, but I don't see any advantage to crashing the thread versus logging the exception and gracefully finishing execution. So one might as well handle the exception rather than rethrowing it, since there will be no one (other than the VM) there to catch it.
Similar Messages
-
Issue with exception Handling in GG
Hi,
I have bi-directional DML replication setup. I have written a code in replication parameter for handling the exception , Exception handling is working fine my replicate process is not getting ABENDED but Issue is I am not geeting any rows in EXCEPTION table.I had gone through replicat report, there I had seen GG is trying to inser duplicate records in EXCEPTION TABLE and it is failing because of that .
**Command for create Exception Table is-**
create table ggs_admin.exceptions (
rep_name varchar2(8) ,
table_name varchar2(61) ,
errno number ,
dberrmsg varchar2(4000) ,
optype varchar2(20) ,
errtype varchar2(20) ,
logrba number ,
logposition number ,
committimestamp timestamp,
CONSTRAINT pk_exceptions PRIMARY KEY (logrba, logposition, committimestamp)
USING INDEX
TABLESPACE INDX1
TABLESPACE dbdat1
My replication parameter is-
GGSCI (db) 1> view params rep2
-- Replicator parameter file to apply changes
REPLICAT rep2
ASSUMETARGETDEFS
USERID ggs_admin, PASSWORD ggs_admin
DISCARDFILE /u01/app/oracle/product/gg/dirdat/rep2_discard.dsc, PURGE
-- Start of the macro
MACRO #exception_handler
BEGIN
, TARGET ggs_admin.exceptions
, COLMAP ( rep_name = "REP2"
, table_name = @GETENV ("GGHEADER", "TABLENAME")
, errno = @GETENV ("LASTERR", "DBERRNUM")
, dberrmsg = @GETENV ("LASTERR", "DBERRMSG")
, optype = @GETENV ("LASTERR", "OPTYPE")
, errtype = @GETENV ("LASTERR", "ERRTYPE")
, logrba = @GETENV ("GGHEADER", "LOGRBA")
, logposition = @GETENV ("GGHEADER", "LOGPOSITION")
, committimestamp = @GETENV ("GGHEADER", "COMMITTIMESTAMP"))
, INSERTALLRECORDS
, EXCEPTIONSONLY;
END;
-- End of the macro
REPERROR (DEFAULT, EXCEPTION)
--REPERROR (-1, EXCEPTION)
--REPERROR (-1403, EXCEPTION)
MAP scr.order_items, TARGET scr.order_items;
MAP scr.order_items #exception_handler();
GGSCI (db) 2>view params rep2
MAP resolved (entry scr.order_items):
MAP "scr"."order_items" TARGET ggs_admin.exceptions , COLMAP ( rep_name = "REP2" , table_name = @GETENV ("GGHEADER", "TABLENAME") , errno = @GETENV ("LASTERR", "DB
ERRNUM") , dberrmsg = @GETENV ("LASTERR", "DBERRMSG") , optype = @GETENV ("LASTERR", "OPTYPE") , errtype = @GETENV ("LASTERR", "ERRTYPE") , logrba = @GETENV ("GGHEADER"
, "LOGRBA") , logposition = @GETENV ("GGHEADER", "LOGPOSITION") , committimestamp = @GETENV ("GGHEADER", "COMMITTIMESTAMP")) , INSERTALLRECORDS , EXCEPTIONSONLY;;
Using the following key columns for target table GGS_ADMIN.EXCEPTIONS: LOGRBA, LOGPOSITION, COMMITTIMESTAMP.
2012-08-30 09:09:00 WARNING OGG-01154 SQL error 1403 mapping scr.order_items to scr.order_items OCI Error ORA-01403: no data found, SQL <DELETE FROM "scr"."order_items" WHERE "SUBSCRIBER_ID" = :b0>.
2012-08-30 09:09:00 WARNING OGG-00869 OCI Error ORA-00001: unique constraint (GGS_ADMIN.PK_EXCEPTIONS) violated (status = 1). INSERT INTO "GGS_ADMIN"."EXCEPTIONS" ("R
EP_NAME","TABLE_NAME","ERRNO","DBERRMSG","OPTYPE","ERRTYPE","LOGRBA","LOGPOSITION","COMMITTIMESTAMP") VALUES (:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8).
2012-08-30 09:09:00 WARNING OGG-01004 Aborted grouped transaction on 'GGS_ADMIN.EXCEPTIONS', Database error 1 (OCI Error ORA-00001: unique constraint (GGS_ADMIN.PK_EX
CEPTIONS) violated (status = 1). INSERT INTO "GGS_ADMIN"."EXCEPTIONS" ("REP_NAME","TABLE_NAME","ERRNO","DBERRMSG","OPTYPE","ERRTYPE","LOGRBA","LOGPOSITION","COMMITTIMES
TAMP") VALUES (:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8)).
2012-08-30 09:09:00 WARNING OGG-01003 Repositioning to rba 92383 in seqno 8.
2012-08-30 09:09:00 WARNING OGG-01154 SQL error 1403 mapping scr.order_items to scr.order_items OCI Error ORA-01403: no data found, SQL <DELETE FROM "scr"."order_items" WHERE "SUBSCRIBER_ID" = :b0>.
2012-08-30 09:09:00 WARNING OGG-01154 SQL error 1 mapping scr.order_items to GGS_ADMIN.EXCEPTIONS OCI Error ORA-00001: unique constraint (GGS_ADMIN.PK_EXCEPTIONS)
violated (status = 1). INSERT INTO "GGS_ADMIN"."EXCEPTIONS" ("REP_NAME","TABLE_NAME","ERRNO","DBERRMSG","OPTYPE","ERRTYPE","LOGRBA","LOGPOSITION","COMMITTIMESTAMP") VAL
UES (:a0,:a1,:a2,:a3,:a4,:a5,:a6,:a7,:a8).
2012-08-30 09:09:00 WARNING OGG-01003 Repositioning to rba 92383 in seqno 8.
When I am running command
select * from exceptions;
no row selected.
Please help. Why duplicat rows trying to insert in Exception table.Remove (disable) the constraint on the exceptions table and see if inserts will take place. Do you really need that primary key?
-
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 for Null/Incorrect input parameters
Hi,
My BI Publisher report has input parameter name as <region>. It is a text field and is mandatory parameter.
But if I run the report without giving value to the parameter it gives the error "The report cannot be rendered because of an error, please contact the administrator."
How can I handle this scenario so that User defined message is displayed, asking user to give correct input.
I am using Oracle BI Publisher 10.1.3.3.3
Is there some documentation available for Exception Handling/How to display User defined messages in case of error?
My requirement is that after displaying the error message (say for example "Please enter Region name"), the report processing should stop there only and it should not display the blank pages of the rest of the PDF template.
Thanks in advance.Hi,
Thanx for the solution.
I have another query linked to this issue. My requirement is that after displaying the error message (say for example "Please enter Customer name"), the report processing should stop there only and it should not display the blank pages of the rest of the PDF template.
Thanx in advance. -
Exception handling in App. package PeopleCode
Hi,
I am accessing a table that is on remote database using DBLink for an update/insert operation using SQLExec. I am trying to implement exception handling to account for the scenario where the remote database is offline so that transaction can continue. However when I use the try-catch block in the app. package PeopleCode somehow the processing does not seem to move forward from the error. The App. pacakage code is triggered by the handler of the service operation. The goal is to simply skip the SQLExec if the table is not available. I am not sure if there is any limitation to the fatal SQL errors which the try-catch can handle.
As expected i get below error when running select on a view which has remote table in the SQL developer as remote database is down.
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
Has anyone enconutered similar issue with exception handling and best way to move forward in this scenario.
Any response is much appreciated.
Thanks,
GireeshI did this with PL/SQL once. Basically, you want to know if the remote database is available before you execute SQL against it. Here is my function. You can then SQLExec something like select 'x' from dual where my_package.link_available('the_link_name') = 1. If you get a result, then the db link is active. If you don't, it is not active.
FUNCTION LINK_AVAILABLE(pv_name VARCHAR2)
RETURN NUMBER AS
lv_result PLS_INTEGER;
lv_name VARCHAR2(128);
BEGIN
lv_name := UPPER(pv_name);
-- parameter check to avoid SQL injection with dynamic SQL below
-- if the following selects no rows, it will fall through to exception
-- and return 0;
SELECT 1
INTO lv_result
FROM ALL_DB_LINKS
WHERE DB_LINK = lv_name;
-- if we made it this far, then the parameter was a valid db link name
-- execute SQL to test
EXECUTE IMMEDIATE 'SELECT 1 FROM PS_INSTALLATION@' || lv_name INTO lv_result;
RETURN lv_result;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END LINK_AVAILABLE; -
Exception Handling in packages called from forms
I am running 10g forms that have many calls to packages/procedures in the database. I am seeing hanging processes on the web server (even after forms processes are stopped) and 1 of the causes Oracle listed was not having proper exception handling in the procesdures. Do I need to add an Exception (' when others then null') to my package specs to handle this?
"Do I need to add an Exception (' when others then null') to my package specs to handle this? "
That will hide the problem not handle it. You really need is to find out where the code is failing...
There is a method for logging message for debugging here...
http://oracle-developer.net/display.php?id=424
An another which is less good for a live system (the one above lets you set different levels of importance for logs messages and can be turned on or off for each user) but looks easier to implement in case you might be in a hurry...
Re: Zdebug -- Download a Forms debugging message tool -
Exception Handling in C++ generate core
Hello ,
I have a shared lib which is having some code for exception handling ,till the point of exception thrown program is running fine but after the exception get thrown the program is crasing and creating the core .
I am using Solaris 5.9 on intel(x86) using compiler CC (CC: Sun C++ 5.5 2003/03/12 )
I am specifing the Makefile here . If any one have faced the same kind of problem then please help me out.
***********************Makefile *****************************
SHARED_LIBS = \
/opt/SUNWspro/prod/lib/libp/libgc.a \
/usr/lib/libCrun.so.1 \
/opt/SUNWspro/prod/lib/CC4/libC.a \
$(WLESSL)/lib/libgp.a \
$(WLESSL)/lib/sslplus.a
LIB=$(OBJ) $(SHARED_LIBS)
LIB128=$(OBJ128) $(SHARED_LIBS)
LIB_20=$(OBJ_20) $(SHARED_LIBS)
CC_20=/opt/SUNWspro/bin/CC
cc_20=/opt/SUNWspro/bin/cc
CC_OUT_20=-w -KPIC -mt -lpthread -c $< -o $@
# compile defintions
DEF=-DAPACHE -DSOLARIS -DEAPI -D_POSIX_PTHREAD_SEMANTICS -D_PTHREAD -D_REENTRANT
DOMFLAG=-DDOMESTIC_STRENGTH_ENABLED
# this is not needed if apache20/bin/apxs is working properly
APXS_CFLAGS_20=-mt -lpthread
COMPILE=$(cc_20) $(APXS_CFLAGS_20) $(STD_20_INC) $(VER2) -c $(SRC) -o $(OBJDIR_20)/abc_w.o
LOAD=$(cc_20) -G -z lazyload -o $(OBJDIR)/abc_wl_20.so $(LIB_20) $(OBJDIR_20)/abc.o
LOAD128=$(cc_20) -G -o $(OBJDIR)/abc_wl128_20.so $(LIB128_20) $(OBJDIR_20)/abc.o
# the DSO and objs should be placed in this directory
OBJDIR=sol_x86
OBJDIR_20=sol_x86/a20
# WLE include files include tmmach which are platform specific
WLESSLINC=$(WLESSL)/sysincludeHi Santinu,
I saw your question and thought of replying you, but I guess you might have got the solution by now as because the post date of your question is around a year back.
You need to change $LOAD so that id uses CC instead of cc. There's a compatibility issue.
LOAD=$(CC_20) -G -z lazyload -o $(OBJDIR)/mod_wl_20.so $(LIB_20) $(OBJDIR_20)/mod_weblogic.o
LOAD128=$(CC_20) -G -o $(OBJDIR)/mod_wl128_20.so $(LIB128_20) $(OBJDIR_20)/mod_weblogic.o
Hope this Helps.
Thanks
Somak -
Exception handling with fault message type not working
Hi,
I have a sync proxy to proxy scenario and I have created a fault MT and specified in the outbound and Inbound service interface...
*In Inbound proxy I have the following code--*......
RAISE EXCEPTION TYPE z_cx_test_fault
EXPORTING
standard = l_standard_data.
In the sender side abap code which calls the outbound proxy I have the follwing code -
CATCH cx_ai_system_fault INTO lo_cx_ai_system_fault.
txt = lo_cx_ai_system_fault->get_text( ).
WRITE txt.
CATCH z_cx_test_fault INTO lo_cx_test_fault.
txt = lo_cx_standard_message_fault->get_text( ).
WRITE txt.
CATCH cx_ai_application_fault INTO lo_cx_ai_application_fault.
txt = lo_cx_ai_application_fault->get_text( ).
WRITE txt.
when i test the inbound proxy separately I get the custom fault message properly...
however when i run the proxy to proxy sync scenario and the custom exceptionz_cx_test_fault is raised inside the receiver proxy .......control goes to CATCH cx_ai_application_fault and not CATCH z_cx_test_fault .
I understand that cx_ai_application_fault is the super class of all the exception class but why does control go to its exception handling when a custom exception is raised...
Edited by: hema T on Feb 26, 2012 1:16 PM
Edited by: hema T on Feb 26, 2012 1:17 PMHi
I tried changing the sequence also but it did not work...
I can see an appropriate response coming from the receiver in SXMB_MONI of PI...this response has the "fault response "
"fault detail" data that I want.....however when the control goes to the sender why does it go to CATCH CX_AI_APPLICATION_FAULT and not not my CATCH z_cx_test_fault .
My observation - If I change the scenario to SOAP to Proxy sync..then the sender SOAP client gets the appropriate custom fault message back.
Edited by: hema T on Feb 27, 2012 1:17 PM
Edited by: hema T on Feb 27, 2012 1:17 PM -
GP Exception handling doesn't work
I had implemented the GP Exception handling scenario described in [Configuring Exception Handling|http://help.sap.com/saphelp_nw2004s/helpdata/en/44/10bd4029450d1be10000000a114a6b/frameset.htm].
But when I start the process and input a wrong user id, the exception handling action doesn't start and the process keep in running status. When I check the Background Action Processor Queue, the queue entry of action "Retrieve User Details" retry executing continously.
And when I check the background callable object, it report that "Obsolete process exception: E_NO_USER_FOUND " in section Process Exceptions Check .
Is it a system bug or Is something wrong in system configuration?
BTW: The environment is NW7.0 SP13 Java StackReposting
-
ADF Faces: Exception Handler activity ain't reraised
Hi there!
I'm using a Studio Edition Version 11.1.1.3.0 (Build JDEVADF_11.1.1.3.PS2_GENERIC_100408.2356.5660).
I've done this:
1. created a bounded task flow flow1 and added to it:
1.1 a vew activity view1 (the default activity) - shows an inputText field for a db column, for which there is a constraint;
1.2 a method call activity method1 - calls commit;
1.3 a view activity view2 - has an ouputText depicting an attribute's value for the same collection as that of inputText in view1;
1.4 a view activity errorView (marked as an exception handler) - displays a localizedMessage from the currentViewPort;
1.5 created for the view activities page fragments (with necessary fields and buttons).
2. linked them as follows:
2.1 view1 -*-> method1 -*-> view2;
2.2 errorView -*-> view1.
3. in the default unbounded task flow created a view activity main, a page file for it, and dropped onto the latter the flow1 as a region;
4. launched the app (as the table contains some data, the view1 displays first row in a row set);
5. entered into the view1 's field a non-violating value;
6. pressed a button (which has just an action property set to move to the method1 ) - everything's fine, we get to the view2;
6. rerun the app;
7. entered incorrect value, pressed the button - flow goes, as expected, to the errorView, which informs us the exception's details (JBO-...);
8. on the errorView page fragment pressed a button - we are now on the view1 page again;
9. left the wrong (violating) value (or changed it to another incorrect value, doesn't matter) and pressed the button again;
10. wow, we reached the view2, but, I guess, we hadn't to. Why so?
One must note, that in clauses 7 and 9, after pressing the button, there apears a popup, which advises us about an ORA-... error, that is, in step 9 the ADF Faces does receive the exception, but why it doesn't reraise the errorView, that's the question.
Though, when I change the method1 so, that it calls a bean's method, which always throws an IllegalArgumentException, then everything works as should to - we get to the infinite loop - view1 -> method1 -> errorView -> view1.
Or, when I extract view2 from flow1, and instead of the former insert return activity with End Transaction set to commit, and then wrap (i.e call) flow1 from a newly created bounded task flow flow2, and in main 's page replace flow1 with flow2 region, the result is quite different. The aforesaid popup with ORA- error arises, until one enters a non-violating value. That is in this case everything is good, except, that control never flows into the errorView.
And there is one more thing to note yet. When I've, namely method1, been calling a bean with the ever exception throwing method, the Integrated WLS's log was silent, but when the method1 was calling commit, then in the log we can see this twice:
<Utils><buildFacesMessage> ADF: Adding the following JSF error message: ORA-02290: check constraint CHECK(THE_USER.THE_CONSTRAINT) violated
java.sql.SQLIntegrityConstraintViolationException: ORA-02290: check constraint CHECK(THE_USER.THE_CONSTRAINT) violated
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:85)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1035)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:953)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1224)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3386)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3467)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
at oracle.jbo.server.OracleSQLBuilderImpl.doEntityDML(OracleSQLBuilderImpl.java:429)
at oracle.jbo.server.EntityImpl.doDML(EntityImpl.java:8044)
at oracle.jbo.server.EntityImpl.postChanges(EntityImpl.java:6373)
at oracle.jbo.server.DBTransactionImpl.doPostTransactionListeners(DBTransactionImpl.java:3172)
at oracle.jbo.server.DBTransactionImpl.postChanges(DBTransactionImpl.java:2980)
at oracle.jbo.server.DBTransactionImpl.commitInternal(DBTransactionImpl.java:2018)
at oracle.jbo.server.DBTransactionImpl.commit(DBTransactionImpl.java:2277)
at oracle.adf.model.bc4j.DCJboDataControl.commitTransaction(DCJboDataControl.java:1577)
at oracle.adf.model.binding.DCDataControl.callCommitTransaction(DCDataControl.java:1404)
at oracle.jbo.uicli.binding.JUCtrlActionBinding.doIt(JUCtrlActionBinding.java:1427)
at oracle.adf.model.binding.DCDataControl.invokeOperation(DCDataControl.java:2141)
at oracle.jbo.uicli.binding.JUCtrlActionBinding.invoke(JUCtrlActionBinding.java:730)
at oracle.adf.controller.v2.lifecycle.PageLifecycleImpl.executeEvent(PageLifecycleImpl.java:394)
at oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding._execute(FacesCtrlActionBinding.java:252)
at oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding.execute(FacesCtrlActionBinding.java:210)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:157)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:283)
at oracle.adf.controller.internal.util.ELInterfaceImpl.invokeMethod(ELInterfaceImpl.java:168)
at oracle.adfinternal.controller.activity.MethodCallActivityLogic.execute(MethodCallActivityLogic.java:161)
at oracle.adfinternal.controller.engine.ControlFlowEngine.executeActivity(ControlFlowEngine.java:989)
at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:878)
at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:777)
at oracle.adfinternal.controller.engine.ControlFlowEngine.routeFromActivity(ControlFlowEngine.java:551)
at oracle.adfinternal.controller.engine.ControlFlowEngine.performControlFlow(ControlFlowEngine.java:147)
at oracle.adfinternal.controller.application.NavigationHandlerImpl.handleAdfcNavigation(NavigationHandlerImpl.java:109)
at oracle.adfinternal.controller.application.NavigationHandlerImpl.handleNavigation(NavigationHandlerImpl.java:78)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:130)
at org.apache.myfaces.trinidad.component.UIXCommand.broadcast(UIXCommand.java:190)
at oracle.adf.view.rich.component.fragment.UIXRegion.broadcast(UIXRegion.java:148)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.broadcastEvents(LifecycleImpl.java:812)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:292)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:191)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:97)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:420)
at oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:420)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:247)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:157)
at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:94)
at java.security.AccessController.doPrivileged(Native Method)
at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:313)
at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:414)
at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:138)
at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.adf.library.webapp.LibraryFilter.doFilter(LibraryFilter.java:159)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.dms.wls.DMSServletFilter.doFilter(DMSServletFilter.java:330)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.doIt(WebAppServletContext.java:3684)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3650)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2268)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2174)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1446)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)What I'm doing wrong? And how can I dismiss that popup, as it duplicates errorView and does not get messages from a custom message bundle?
Thanks in advance for any comments.
Yerzhan.Hi there!
I'm using a Studio Edition Version 11.1.1.3.0 (Build JDEVADF_11.1.1.3.PS2_GENERIC_100408.2356.5660).
I've done this:
1. created a bounded task flow flow1 and added to it:
1.1 a vew activity view1 (the default activity) - shows an inputText field for a db column, for which there is a constraint;
1.2 a method call activity method1 - calls commit;
1.3 a view activity view2 - has an ouputText depicting an attribute's value for the same collection as that of inputText in view1;
1.4 a view activity errorView (marked as an exception handler) - displays a localizedMessage from the currentViewPort;
1.5 created for the view activities page fragments (with necessary fields and buttons).
2. linked them as follows:
2.1 view1 -*-> method1 -*-> view2;
2.2 errorView -*-> view1.
3. in the default unbounded task flow created a view activity main, a page file for it, and dropped onto the latter the flow1 as a region;
4. launched the app (as the table contains some data, the view1 displays first row in a row set);
5. entered into the view1 's field a non-violating value;
6. pressed a button (which has just an action property set to move to the method1 ) - everything's fine, we get to the view2;
6. rerun the app;
7. entered incorrect value, pressed the button - flow goes, as expected, to the errorView, which informs us the exception's details (JBO-...);
8. on the errorView page fragment pressed a button - we are now on the view1 page again;
9. left the wrong (violating) value (or changed it to another incorrect value, doesn't matter) and pressed the button again;
10. wow, we reached the view2, but, I guess, we hadn't to. Why so?
One must note, that in clauses 7 and 9, after pressing the button, there apears a popup, which advises us about an ORA-... error, that is, in step 9 the ADF Faces does receive the exception, but why it doesn't reraise the errorView, that's the question.
Though, when I change the method1 so, that it calls a bean's method, which always throws an IllegalArgumentException, then everything works as should to - we get to the infinite loop - view1 -> method1 -> errorView -> view1.
Or, when I extract view2 from flow1, and instead of the former insert return activity with End Transaction set to commit, and then wrap (i.e call) flow1 from a newly created bounded task flow flow2, and in main 's page replace flow1 with flow2 region, the result is quite different. The aforesaid popup with ORA- error arises, until one enters a non-violating value. That is in this case everything is good, except, that control never flows into the errorView.
And there is one more thing to note yet. When I've, namely method1, been calling a bean with the ever exception throwing method, the Integrated WLS's log was silent, but when the method1 was calling commit, then in the log we can see this twice:
<Utils><buildFacesMessage> ADF: Adding the following JSF error message: ORA-02290: check constraint CHECK(THE_USER.THE_CONSTRAINT) violated
java.sql.SQLIntegrityConstraintViolationException: ORA-02290: check constraint CHECK(THE_USER.THE_CONSTRAINT) violated
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:85)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1035)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:953)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1224)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3386)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3467)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
at oracle.jbo.server.OracleSQLBuilderImpl.doEntityDML(OracleSQLBuilderImpl.java:429)
at oracle.jbo.server.EntityImpl.doDML(EntityImpl.java:8044)
at oracle.jbo.server.EntityImpl.postChanges(EntityImpl.java:6373)
at oracle.jbo.server.DBTransactionImpl.doPostTransactionListeners(DBTransactionImpl.java:3172)
at oracle.jbo.server.DBTransactionImpl.postChanges(DBTransactionImpl.java:2980)
at oracle.jbo.server.DBTransactionImpl.commitInternal(DBTransactionImpl.java:2018)
at oracle.jbo.server.DBTransactionImpl.commit(DBTransactionImpl.java:2277)
at oracle.adf.model.bc4j.DCJboDataControl.commitTransaction(DCJboDataControl.java:1577)
at oracle.adf.model.binding.DCDataControl.callCommitTransaction(DCDataControl.java:1404)
at oracle.jbo.uicli.binding.JUCtrlActionBinding.doIt(JUCtrlActionBinding.java:1427)
at oracle.adf.model.binding.DCDataControl.invokeOperation(DCDataControl.java:2141)
at oracle.jbo.uicli.binding.JUCtrlActionBinding.invoke(JUCtrlActionBinding.java:730)
at oracle.adf.controller.v2.lifecycle.PageLifecycleImpl.executeEvent(PageLifecycleImpl.java:394)
at oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding._execute(FacesCtrlActionBinding.java:252)
at oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding.execute(FacesCtrlActionBinding.java:210)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:157)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:283)
at oracle.adf.controller.internal.util.ELInterfaceImpl.invokeMethod(ELInterfaceImpl.java:168)
at oracle.adfinternal.controller.activity.MethodCallActivityLogic.execute(MethodCallActivityLogic.java:161)
at oracle.adfinternal.controller.engine.ControlFlowEngine.executeActivity(ControlFlowEngine.java:989)
at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:878)
at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:777)
at oracle.adfinternal.controller.engine.ControlFlowEngine.routeFromActivity(ControlFlowEngine.java:551)
at oracle.adfinternal.controller.engine.ControlFlowEngine.performControlFlow(ControlFlowEngine.java:147)
at oracle.adfinternal.controller.application.NavigationHandlerImpl.handleAdfcNavigation(NavigationHandlerImpl.java:109)
at oracle.adfinternal.controller.application.NavigationHandlerImpl.handleNavigation(NavigationHandlerImpl.java:78)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:130)
at org.apache.myfaces.trinidad.component.UIXCommand.broadcast(UIXCommand.java:190)
at oracle.adf.view.rich.component.fragment.UIXRegion.broadcast(UIXRegion.java:148)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.broadcastEvents(LifecycleImpl.java:812)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:292)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:191)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:97)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:420)
at oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:420)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:247)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:157)
at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:94)
at java.security.AccessController.doPrivileged(Native Method)
at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:313)
at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:414)
at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:138)
at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.adf.library.webapp.LibraryFilter.doFilter(LibraryFilter.java:159)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.dms.wls.DMSServletFilter.doFilter(DMSServletFilter.java:330)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.doIt(WebAppServletContext.java:3684)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3650)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2268)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2174)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1446)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)What I'm doing wrong? And how can I dismiss that popup, as it duplicates errorView and does not get messages from a custom message bundle?
Thanks in advance for any comments.
Yerzhan. -
Never implemented exception handling in Stored Procedures
I have lots of stand alone stored procedures callled from .NET 20 programs that follow the following pattern. They runn against Oracle 10.2 on Win2003. The only deviiation is a couple where I insert to temptables. I specify a parameter for messages but don't know the best way to implement for Oracle as well as any tips on ODP.NET/oracle interactions error handling.
1. Is it recommended to implement exception handling in With Clauses?
2. If there is an exception in one cursor's SQL, how do I still execute the second?
3. Is it best in some circumstances to pass a null back to client and check for null in program?
From .NET programs I have run into a couple of problems.
4. TNS packet failure.
Anyways any suggestions or experiences are welcome.
CREATE OR REPLACE PROCEDURE GET_SALES_DATA
, p_businessdate in date
, p_message out varchar2
, p_rcSales out sys_refcursor
, p_rInventory out sys_refcursor
) is
open p_rcSales for
with somedata as (select ...)
, someMoreData as (selct ...)
-- Main select
Select * from somedata sd inner join somemoredata smd on smd.key = sd.key;
open p_rcInventory for
with somedata as (select ...)
, someMoreData as (selct ...)
-- Main select
Select * from somedata sd inner join somemoredata smd on smd.key = sd.key;
-- CODE NOT IMPLEMENTED
-- exception
-- when TOO_MANY_ROWS then select 'Error handling for future implementations' into p_message from dual ;
-- when NO_DATA_FOUND then select 'Error handling for future implementations. No data' into p_message from dual;
-- when others then raise_application_error(-20011,'Unknown Exception in GET_SALES_DATA Function');
-- WHEN invalid_business_date then select 'Invalid: Business date is in the current work week.' into p_message from dual ;
END GET_SALES_DATA;Pseudocode'ish because Module level variables and properties have not been defined here for brevity.
Public Class WebPage1
PAge_Load
GetData
End Class Data Access Layer
Public Class DAL
Public Sub GetOracleData()
Dim conn As OracleConnection
Try
conn = New OracleConnection
Catch ex As Exception
Throw ex
End Try
Dim cmd As New OracleCommand
With cmd
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
cmd.CommandText = DATABASE.GetSalesData
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
End With
cmd.Connection = conn
Dim oparam As OracleParameter
oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
oparam.Value = BusinessDate.ToString("dd-MMM-yy")
oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rc_inven_csv", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
Dim Adapter As New OracleDataAdapter(cmd)
Try
Adapter.TableMappings.Add("Table", Sales)
Adapter.TableMappings.Add("Table1", Inventory)
Adapter.Fill(dsOracleData)
Catch ex As OracleException
HandleError("Exception Retrieving Oracle Data", ex, MethodInfo.GetCurrentMethod.Name, True)
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
dbMessages = cmd.Parameters("p_message").ToString
End If
arrStatusMessages.Add("Retrieved Oracle Data Successfully")
End Sub
' Original Implementation ; No longer used
Public function GetOracleData
Dim conn As New OracleConnection
conn.ConnectionString = dbconn.Connectionstring
Dim cmd As New OracleCommand
With cmd
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
cmd.CommandText = DATABASE.GetSalesData
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
End With
cmd.Connection = conn
Dim oparam As OracleParameter
oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
oparam.Value = BusinessDate.ToString("dd-MMM-yy")
oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
Dim Adapter As New OracleDataAdapter(cmd)
Try
Adapter.TableMappings.Add("Table", Sales)
Adapter.TableMappings.Add("Table1", Inventory)
Adapter.Fill(dsOracleData)
dim dt as datatable = dsoracledata.tables("sales")
If IsDataNull(dt) Then
_errorType = DBErrorType.NullData
End If
If isDataEmpty(dt) Then
_errorType = DBErrorType.EmptyData
End If
_hasError = False
Catch oraEx As OracleException
_ExceptionText = oraEx.Message.ToString
_errorType = DBErrorType.OracleException
#If DEBUG Then
Throw oraEx
#End If
Catch zeroEx As DivideByZeroException
_ExceptionText = zeroEx.Message.ToString
_errorType = DBErrorType.DivideByZeroException
#If DEBUG Then
Throw zeroEx
#End If
Catch oflowEx As OverflowException
_ExceptionText = oflowEx.Message.ToString
_errorType = DBErrorType.OverflowException
#If DEBUG Then
Throw oflowEx
#End If
Catch argEx As InsufficientMemoryException
_ExceptionText = argEx.Message.ToString
_errorType = DBErrorType.InsufficientMemoryException
#If DEBUG Then
Throw argEx
#End If
Catch nomemEx As OutOfMemoryException
_ExceptionText = nomemEx.Message.ToString
_errorType = DBErrorType.OutOfMemoryException
#If DEBUG Then
Throw nomemEx
#End If
Catch Ex As Exception
_ExceptionText = Ex.Message.ToString
_errorType = DBErrorType.GenericException
#If DEBUG Then
Throw Ex
#End If
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
End class Error Class
Public Class Errors
Public Sub ExitClass()
Return
End Sub
' 'blnWriteNow says when Error is critical and no further processing needs to be done by class, then write to event logs or text files and call exit class
' to return control back to webpage. This is my first time trying this way.
Public Sub HandleError(ByVal friendlyMsg As String, ByVal objEx As Exception, ByVal methodInfo As String, Optional ByVal blnWriteNow As Boolean = False)
If Not blnWriteNow Then Exit Sub
Dim strMessages As String
strMessages = arrStatusMessages
'Send error email
If blnSendEmails Then
SendMail("[email protected], strMessages. applicationname, " has thrown error. ")
End If
'Throw error for debugging
If blnThrowErrors Then
Throw New Exception(strMessages & vbCrLf & objEx.Message)
End If
' Write to event log and if not available (shared hosting environment), write to text log
If blnWriteNow Then
If blnWriteToEvtLog Then
If blnCanWriteToEvtLog Then 'Program has write permission to log
WriteToEventLog(strMessages, _appname, EventLogEntryType.Error, appname)
Else
If Not Directory.Exists( appPath & "\log") Then
Try
Directory.CreateDirectory( appPath & "\log")
Catch ex As Exception
arrStatusMessages.Add("Cant't write to event log or create a directory")
End Try
End If
End If
End If
End If
End Sub
End ClassI have lots of stand alone stored procedures callled from .NET 20 programs that follow the following pattern. They runn against Oracle 10.2 on Win2003. The only deviiation is a couple where I insert to temptables. I specify a parameter for messages but don't know the best way to implement for Oracle as well as any tips on ODP.NET/oracle interactions error handling.
1. Is it recommended to implement exception handling in With Clauses?
2. If there is an exception in one cursor's SQL, how do I still execute the second?
3. Is it best in some circumstances to pass a null back to client and check for null in program?
From .NET programs I have run into a couple of problems.
4. TNS packet failure.
Anyways any suggestions or experiences are welcome.
CREATE OR REPLACE PROCEDURE GET_SALES_DATA
, p_businessdate in date
, p_message out varchar2
, p_rcSales out sys_refcursor
, p_rInventory out sys_refcursor
) is
open p_rcSales for
with somedata as (select ...)
, someMoreData as (selct ...)
-- Main select
Select * from somedata sd inner join somemoredata smd on smd.key = sd.key;
open p_rcInventory for
with somedata as (select ...)
, someMoreData as (selct ...)
-- Main select
Select * from somedata sd inner join somemoredata smd on smd.key = sd.key;
-- CODE NOT IMPLEMENTED
-- exception
-- when TOO_MANY_ROWS then select 'Error handling for future implementations' into p_message from dual ;
-- when NO_DATA_FOUND then select 'Error handling for future implementations. No data' into p_message from dual;
-- when others then raise_application_error(-20011,'Unknown Exception in GET_SALES_DATA Function');
-- WHEN invalid_business_date then select 'Invalid: Business date is in the current work week.' into p_message from dual ;
END GET_SALES_DATA;Pseudocode'ish because Module level variables and properties have not been defined here for brevity.
Public Class WebPage1
PAge_Load
GetData
End Class Data Access Layer
Public Class DAL
Public Sub GetOracleData()
Dim conn As OracleConnection
Try
conn = New OracleConnection
Catch ex As Exception
Throw ex
End Try
Dim cmd As New OracleCommand
With cmd
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
cmd.CommandText = DATABASE.GetSalesData
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
End With
cmd.Connection = conn
Dim oparam As OracleParameter
oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
oparam.Value = BusinessDate.ToString("dd-MMM-yy")
oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rc_inven_csv", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
Dim Adapter As New OracleDataAdapter(cmd)
Try
Adapter.TableMappings.Add("Table", Sales)
Adapter.TableMappings.Add("Table1", Inventory)
Adapter.Fill(dsOracleData)
Catch ex As OracleException
HandleError("Exception Retrieving Oracle Data", ex, MethodInfo.GetCurrentMethod.Name, True)
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
dbMessages = cmd.Parameters("p_message").ToString
End If
arrStatusMessages.Add("Retrieved Oracle Data Successfully")
End Sub
' Original Implementation ; No longer used
Public function GetOracleData
Dim conn As New OracleConnection
conn.ConnectionString = dbconn.Connectionstring
Dim cmd As New OracleCommand
With cmd
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
cmd.CommandText = DATABASE.GetSalesData
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
End With
cmd.Connection = conn
Dim oparam As OracleParameter
oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
oparam.Value = BusinessDate.ToString("dd-MMM-yy")
oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
Dim Adapter As New OracleDataAdapter(cmd)
Try
Adapter.TableMappings.Add("Table", Sales)
Adapter.TableMappings.Add("Table1", Inventory)
Adapter.Fill(dsOracleData)
dim dt as datatable = dsoracledata.tables("sales")
If IsDataNull(dt) Then
_errorType = DBErrorType.NullData
End If
If isDataEmpty(dt) Then
_errorType = DBErrorType.EmptyData
End If
_hasError = False
Catch oraEx As OracleException
_ExceptionText = oraEx.Message.ToString
_errorType = DBErrorType.OracleException
#If DEBUG Then
Throw oraEx
#End If
Catch zeroEx As DivideByZeroException
_ExceptionText = zeroEx.Message.ToString
_errorType = DBErrorType.DivideByZeroException
#If DEBUG Then
Throw zeroEx
#End If
Catch oflowEx As OverflowException
_ExceptionText = oflowEx.Message.ToString
_errorType = DBErrorType.OverflowException
#If DEBUG Then
Throw oflowEx
#End If
Catch argEx As InsufficientMemoryException
_ExceptionText = argEx.Message.ToString
_errorType = DBErrorType.InsufficientMemoryException
#If DEBUG Then
Throw argEx
#End If
Catch nomemEx As OutOfMemoryException
_ExceptionText = nomemEx.Message.ToString
_errorType = DBErrorType.OutOfMemoryException
#If DEBUG Then
Throw nomemEx
#End If
Catch Ex As Exception
_ExceptionText = Ex.Message.ToString
_errorType = DBErrorType.GenericException
#If DEBUG Then
Throw Ex
#End If
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
End class Error Class
Public Class Errors
Public Sub ExitClass()
Return
End Sub
' 'blnWriteNow says when Error is critical and no further processing needs to be done by class, then write to event logs or text files and call exit class
' to return control back to webpage. This is my first time trying this way.
Public Sub HandleError(ByVal friendlyMsg As String, ByVal objEx As Exception, ByVal methodInfo As String, Optional ByVal blnWriteNow As Boolean = False)
If Not blnWriteNow Then Exit Sub
Dim strMessages As String
strMessages = arrStatusMessages
'Send error email
If blnSendEmails Then
SendMail("[email protected], strMessages. applicationname, " has thrown error. ")
End If
'Throw error for debugging
If blnThrowErrors Then
Throw New Exception(strMessages & vbCrLf & objEx.Message)
End If
' Write to event log and if not available (shared hosting environment), write to text log
If blnWriteNow Then
If blnWriteToEvtLog Then
If blnCanWriteToEvtLog Then 'Program has write permission to log
WriteToEventLog(strMessages, _appname, EventLogEntryType.Error, appname)
Else
If Not Directory.Exists( appPath & "\log") Then
Try
Directory.CreateDirectory( appPath & "\log")
Catch ex As Exception
arrStatusMessages.Add("Cant't write to event log or create a directory")
End Try
End If
End If
End If
End If
End Sub
End Class -
I have a perplexing question.... I am in the midst of developing an APEX 4.0 application. Customer will NOT be going to4.1 for a while....I wish to have exception handling that will handle both APEX based interactions and some back-end Sql Loader activity.
I have built an Exception handler that has a supporting APEX page to display a more human compatible error page, but am trying to make the exception handler NOT try and call up a page and such if the exception it encounters is a trigger being fired when a # of rows are being bulked loaded..
Simply put.. In the exception handler, how can I have code branch around the fact I might NOT have an APEX application for it to display the error ...
What I'd love to find is an object or variable that tells me what I am running the PL/SQL under..
Thank you,
Tony Miller
Dallas, TxJari,
If I try running this from SQL Plus, I would assume it would crash due to fact I am NOT running under APEX and can NOT see the Application object that this function is based upon:
IS_SESSION_VALID Function
This function is a Boolean result obtained from executing the current application's authentication scheme to determine if a valid session exists. This function returns the Boolean result of the authentication scheme's page sentry.
Its like trying to figure out which came 1st, the chicken or the egg...
Thank you,
Tony Miller
Dallas, TX -
Handle long-running EDT tasks (f.i. TreeModel searching)
Note: this is a cross-post from SO
http://stackoverflow.com/questions/9378232/handle-long-running-edt-tasks-f-i-treemodel-searching
copied below, input highly appreciated :-)
Cheers
Jeanette
Trigger is a recently re-detected SwingX issue (https://java.net/jira/browse/SWINGX-1233): support deep - that is under collapsed nodes as opposed to visible nodes only, which is the current behaviour - node searching.
"Nichts leichter als das" with all my current exposure to SwingWorker: walk the TreeModel in the background thread and update the ui in process, like shown in a crude snippet below. Fest's EDT checker is happy enough, but then it only checks on repaint (which is nicely happening on the EDT here)
Only ... strictly speaking, that background thread must be the EDT as it is accessing (by reading) the model. So, the questions are:
- how to implement the search thread-correctly?
- or can we live with that risk (heavily documented, of course)
One possibility for a special case solution would be to have a second (cloned or otherwise "same"-made) model for searching and then find the corresponding matches in the "real" model. That doesn't play overly nicely with a general searching support, as that can't know anything about any particular model, that is can't create a clone even if it wanted. Plus it would have to apply all the view sorting/filtering (in future) ...
// a crude worker (match hard-coded and directly coupled to the ui)
public static class SearchWorker extends SwingWorker<Void, File> {
private Enumeration enumer;
private JXList list;
private JXTree tree;
public SearchWorker(Enumeration enumer, JXList list, JXTree tree) {
this.enumer = enumer;
this.list = list;
this.tree = tree;
@Override
protected Void doInBackground() throws Exception {
int count = 0;
while (enumer.hasMoreElements()) {
count++;
File file = (File) enumer.nextElement();
if (match(file)) {
publish(file);
if (count > 100){
count = 0;
Thread.sleep(50);
return null;
@Override
protected void process(List<File> chunks) {
for (File file : chunks) {
((DefaultListModel) list.getModel()).addElement(file);
TreePath path = createPathToRoot(file);
tree.addSelectionPath(path);
tree.scrollPathToVisible(path);
private TreePath createPathToRoot(File file) {
boolean result = false;
List<File> path = new LinkedList<File>();
while(!result && file != null) {
result = file.equals(tree.getModel().getRoot());
path.add(0, file);
file = file.getParentFile();
return new TreePath(path.toArray());
private boolean match(File file) {
return file.getName().startsWith("c");
// its usage in terms of SwingX test support
public void interactiveDeepSearch() {
final FileSystemModel files = new FileSystemModel(new File("."));
final JXTree tree = new JXTree(files);
tree.setCellRenderer(new DefaultTreeRenderer(IconValues.FILE_ICON, StringValues.FILE_NAME));
final JXList list = new JXList(new DefaultListModel());
list.setCellRenderer(new DefaultListRenderer(StringValues.FILE_NAME));
list.setVisibleRowCount(20);
JXFrame frame = wrapWithScrollingInFrame(tree, "search files");
frame.add(new JScrollPane(list), BorderLayout.SOUTH);
Action traverse = new AbstractAction("worker") {
@Override
public void actionPerformed(ActionEvent e) {
setEnabled(false);
Enumeration fileEnum = new PreorderModelEnumeration(files);
SwingWorker worker = new SearchWorker(fileEnum, list, tree);
PropertyChangeListener l = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
//T.imeOut("search end ");
setEnabled(true);
((SwingWorker) evt.getSource()).removePropertyChangeListener(this);
worker.addPropertyChangeListener(l);
// T.imeOn("starting search ... ");
worker.execute();
addAction(frame, traverse);
show(frame)
}At the end of the day, it turned out that I asked the wrong question (or right question in a wrong context ;-): the "problem" arose by an assumed solution, the real task to solve is to support a hierarchical search algorithm (right now the AbstractSearchable is heavily skewed on linear search).
Once that will solved, the next question might be how much a framework can do to support concrete hierarchical searchables. Given the variety of custom implementations of TreeModels, that's most probably possible only for the most simple.
Some thoughts that came up in the discussions here and the other forums. In a concrete context, first measure if the traversal is slow: most in-memory models are lightning fast to traverse, nothing needs to be done except using the basic support.
Only if the traversal is the bottleneck (as f.i. in the FileSystemModel implementations of SwingX) additional work is needed:
- in a truly immutable and unmodifiable TreeModel we might get away with read-only access in a SwingWorker's background thread
- the unmodifiable precondition is violated in lazy loading/deleting scenarios
there might be a natural custom data structure which backs the model, which is effectively kind-of "detached" from the actual model which allows synchronization to that backing model (in both traversal and view model)
- pass the actual search back to the database
- use an wrapper on top of a given TreeModel which guarantees to access the underlying model on the EDT
- "fake" background searching: actually do so in small-enough blocks on the EDT (f.i. in a Timer) so that the user doesn't notice any delay
Whatever the technical option to a slow search, there's the same usability problem to solve: how to present the delay to the end user? And that's an entirely different story, probably even more context/requirement dependent :-)
Thanks for all the valuable input!
Jeanette -
Hello. In my applications I usually have a try catch(Throwable) block surrounding all the top code (the code in main()) to log and report errors and exceptions that is not caught anywhere else, and to have my application exit in a controlled way. But I recently noticed that exceptions thrown in event handling (i.e. java.awt.EventDispatchThread.run) are not caught by the try catch block in main().
Are there any easy way to catch everything so my app can exit in a controlled way?
If this is not possible which exceptions are not propagated to main()? I would guess that it's exceptions thrown in other threads, is this correct? If so, do I have to surround all event handling by try catch(Throwable) to be safe?
I would like more information and guidelines about exception handling. Any book recommendations?
Help appreciated, thanks!You should never let exceptions propagate outside your event handling methods.
If you don't follow that rule, the java.awt.EventDispatchThread.run() method terminates and the Java Virtual Machine tries to print the stack trace to the terminal window (if there is one) and then exits, but not through your main() method.
So, try /catch all Exceptions inside your event handler methods:
// inside event handler method
try {
// handle event here
} catch (Throwable t) {
// handle errors and recover from errors here
// and either log error or if important display message to the user.
}There is no easy-lazy way to do exception handling by only having the try/catch block in main in this case.
Note : If any of the listeners throws an exception none of the following listeners is called. Since there is no guarantee of the order in which listeners are called you cannot be sure which ones are called first. -
Exception Handling Concept Gone Bad!!
Okay, this is by far the most embarrassing hack of code I've done thus far . . . but it works. I am trying to run a select where if there is no data or null returned, place it into the value "v_pidm', and then let the action occur. Simple enough, right? Wrong! A select that return no data which is using a 'into' function is an exception . . . "no data found." Oracle sends this to the exception block as it should. Okay, I don't want to stop and start my script a million times, there I added an sub Begin/End with an exception to handle the say error and perform an insert. I know you shouldn't use an exception state for inserts another than capturing errors . . . you know bad practices and all. Any ideas as how to better handle the select statement that should regularly return no data? I was thinking about some along the line of nvl(v_pidm, 0) or something, but I am getting errors.
set serveroutput ON SIZE 1000000
set heading off
set feedback off
set trimspool off
set echo off
set pagesize 0
set termout on
Declare
error varchar(255);
v_pidm number(8);
Begin
Begin
select distinct saraatt_pidm
into
v_pidm
from saraatt, saradap
where saraatt_appl_no = SARADAP_APPL_NO
and saraatt_term_code = SARADAP_TERM_CODE_ENTRY
and saraatt_pidm = 4;
Exception
when too_many_rows then
error := SQLERRM;
DBMS_OUTPUT.PUT_LINE(' %% Oracle Error! %% The select statement returned more than two rows ');
when no_data_found then
error := SQLERRM;
DBMS_OUTPUT.PUT_LINE('Select Returned No Data . . . Therefore Insert new record for ' || v_pidm );
v_pidm := -999;
when others then
error := SQLERRM;
DBMS_OUTPUT.PUT_LINE(' %% Oracle Error! %% An Error Occured ' || substr(error,5,20));
End;
DBMS_OUTPUT.PUT_LINE('Pidm: ' || v_pidm);
End;it would be better to just let the exception get propagated up so that you can see the full error stack.
Agrees fully with Justin
@Pr****
It took me a while as well, but in the end the best thing to do is avoid a WHEN OTHERS at all cost.
Once you resort to it, you're actually hiding some flaw(s), it might be design (it usually is)....or whatever, and the database covers up for t, and gets the blame.
And it's a pet-peeve of Tom Kyte for quite a while, and he wrote very good articles on it, do some readng on them:
http://google.com/search?q=site%3Atkyte.blogspot.com+%22when+others%22
Okay, I don't want to stop and start my script a million times, there I added an sub Begin/End with an exception to handle the say error and perform an insertYour example also doesn't seem to show the complete picture then?
I see no INSERT statement?
You have hidden your complete block structure, which makes it hard to guess what's going on/help you.
Perhaps you've nested your example in real life in another block, having it's own exception handler and so on...
I am getting errors.If you're getting errors and want some volunteers to help, then why not just post the full error message as well?
And your database version (the result of: select * from v$version; )
Maybe you are looking for
-
HI, My upgrade from 3.1 to 4.0 has been going smoothly up to now. It stopped in phase REQ_BBWPCRM now asking me to perform the actions in the chapter 'Follow-up activities for the Middleware' in the documentation 'Upgrade Guide - CRM 5.0'. No mention
-
Is there some way to make the iPad Camera Connection Kit work on the iPod touch?
I bought the Camera Connection Kit because a tech said it would work with my iPod Touch, but I get the message that the iPod does not support that connection. I would really like itt to work because I have used an older iPod to back up photos while o
-
I am leaving my job and we have been uploading all of my InDesign files onto Google Drive to prepare, so that my boss/coworkers can use and access my work. My boss has found that he can't download the files without the photos in the documents turning
-
Document Storage in Sharepoint without using EP
Hi, We are implementing SAP Solution Manager 4.0 without using EP. It uses CRM 5.0. The issue We are facing is that the Content Management system of CRM 5.0 uses the SAP databases for storage of documents. Obviously, this can be expected to be a heav
-
Belkin AV360 Converter with 27" iMac
I bought the converter online from the Apple Store and it arrived today. I installed the plug and play cords provided with the converter. I then connected HDMI cable from my Directv receiver into the converter. My problem is with the sound. The sound