Exceptions handling (finally)
try {
catch {
finally {
What is the purpose of "finally" if I can catch an error using "catch"? Any example?
Thanks,
http://java.sun.com/docs/books/tutorial/essential/exceptions/index.htmlIt's for cleanup code that will get executed regardless of how and where the try and catch blocks complete. Throw, return, normal completion--regardless, the finally block will execute.
Similar Messages
-
Best Practice for Implementing Exception Handling in BPEL
Hi All,
what is the best practice and the approach to follow Exception Handling in BPEL.
1) Do we need to implement Exception Handling in BPEL as we do in Java, means
method 3 throws error to method 2 (if any) and
method 2 throws error to method 1 (if any) and
finally method 1 throws error to the main Class.
If we replicate the above scenario to BPEL
In BPEL main Scope have Custom Fault, Catch ALL
Each Invoke is surrounded by a Scope Activity with Remote Fault, Binding Fault & Custom Fault
and follow the paradigm of Java, assuming we have Inner Scopes
[ OR ]
2) In BPEL main Scope have all exceptions defined like
Remote Fault,
Binding Fault,
anyOther System Fault (selectionFailure / forcedTermination),
Custom Fault (if required) and
CatchALL
and also
each Invoke is surrounded by a Scopes Acitivity with Custom Fault (business fault) exception Handling
I feel 1st one may not be a good practice, may be i am wrong...
Any Suggestions from experts.
Thanks in Advance
anvv sharmaHi-
In you can create different scope and use catch branch to catch binding, remote, custom faults, business faults etc. If an error happens in a scope it will not move to the next scope( eg: you have 3 scope, error occured in 2nd scope then it will not propogate to the 3rd scope. One thing to be noticed here is your transaction in the 1st scope doesnt gets commited when an error happens in 2d scope).
You can have a catch all to catch error which are not being caught at catch level. So if any error happens which is not defined in catch block then then it will be caught in catch all branch.
Edited by: 333333 on Apr 12, 2011 9:39 AM -
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". -
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? -
Exception handling in File to IDoc Scenario
Hi,
I have successfully configured File to IDoc Scenario. Now I want to include some exception handling which should be capable of create a mail to recipient when a mapping error occurs.
Can anybody help me out?
Regards,
Suraj KumarHi Suraj,
A few points while creating ALERTS.
<b>TESTING YOUR ALERT CONFIGURATIOn</b>
go to <b>se37 --></b> and <b>execute the report RSALERTTEST</b>. GIve your ALERT CATEGORY in this report. If your ALERTS are configured properly, then your Alert would be triggered and you can see the entry in ALERT INBBOX.
<b>ALERT RULE</b>
Make sure that in your Alert Rule, <b>the option Suppress Multiple Alerts of this rule has not been seelcted</b>.
Finally, if you are on SP14 and above check this note <b>913858</b> for alerts.
If you are below Sp14, then this blog can help you set the background processes needed.
/people/michal.krawczyk2/blog/2005/09/09/xi-alerts--troubleshooting-guide
No BPMis needed to trigger alerts in either case.
Do get back for any clarifications,
Regards,
Bhavesh -
Exception Handling related problem
Can anybody tell me why it is not giving ArithmeticException.
package pckg1;
* @author anil_saini
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
import java.io.FileNotFoundException;
public class Average7 {
public static void main(String[] args) throws InterruptedException,FileNotFoundException {
try { // (1) System.out.println(printAverage(100, 0)); // (2)
} catch (ArithmeticException ae) { // (3)
Thread.sleep(1000);
ae.printStackTrace(); // (4)
System.out.println("Exception handled in " + // (5)
"main().");
finally {
System.out.println("Finally in main()."); // (6)
System.out.println("Exit main()."); // (7)
public static int printAverage(int totalSum, int totalNumber) {
int average=0;
try { // (8)
average = computeAverage(totalSum, totalNumber); // (9)
System.out.println("Average = " + // (10)
totalSum + " / " + totalNumber + " = " + average);
return average;
} catch (IllegalArgumentException iae) { // (11)
iae.printStackTrace(); // (12)
System.out.println("Exception handled in " + // (13)
"printAverage().");
} finally {
System.out.println("Finally in printAverage()."); // (14)
return average;
} // (15)
public static int computeAverage(int sum, int number) {
System.out.println("Computing average.");
if (number == 0) // (16)
throw new ArithmeticException("Integer division by 0");// (17)
return sum/number; // (18)
Output
=======================
Computing average.
Finally in printAverage().
0
Finally in main().
Exit main().Because return statements in finally blocks are evil!
int average = 0;
try
{ // (8)
average = computeAverage(totalSum, totalNumber); // (9)
System.out.println("Average = " + // (10)
totalSum + " / " + totalNumber + " = " + average);
return average;
catch (IllegalArgumentException iae)
{ // (11)
iae.printStackTrace(); // (12)
System.out.println("Exception handled in " + // (13)
"printAverage().");
throw new IllegalArgumentException();
finally
System.out.println("Finally in printAverage()."); // (14)
return average; // (15)
}You get an exception at (9), but finally is guaranteed to be executed, so the JVM executes it. Now you return in your finally block (15), and the JVM is left with the choice of executing your return statement or propagating the exception. Since, as said, finally is guaranteed to be executed, it returns and swallows the exception.
That's why IMHO return statements in finally blocks should not be allowed.
(Some compilers issue warnings)
If you move your return statement out of the finally block, it will work as you'd expect it. -
Exception handling bug in EJB-s
Hi,
My collegue had problems with exceptions in iPlanet EJB-s.
Exceptions that were inherited from the class that is declared to be
thrown by a particular method made EJB-s to be destroyed due to an
unhadled exception. (Eg. NoSuchObjectException is found to be unhandled
even if FinderException is declared to be thrown.)
This is a serious malfunction of the container and against the basic
concept of EJB and also the Java itself.
The root cause that were found is highlighted in the code example, where
direct equality is used for testing class instead of the instanceof
operator. This code has been found in ejb_skel_CLASSNAME.java and has
been generatd by ejbc iAS6 SP3.
Regards,
Gy�rgy Szondy
Capital Systems Kft.
Gy�rgy Szondy, Development Team Manager
Gogol u. 16., 1133 Budapest, Hungary
Tel: +36 1 288 7036 mailto:[email protected]
Fax: +36 1 350 8159
-----Eredeti �zenet-----
Felad�: Geiszter Gy�rgy
Elk�ldve: 2001.okt�ber.8. 14:23
C�mzett: Szondy Gy�rgy
T�rgy: Exception handling in EJB-s
public void removePerson(int arg0) throws java.rmi.RemoteException,
hu.capsys.wwwsol.control.WwwsolException
Object delegate = super._ns_getDelegateForUpCall();
try
nsbeforeUpcall("removePerson", delegate);
try
delegate.getClass().getMethod("removePerson", new Class[]{
Integer.TYPE}).invoke(delegate, new Object[]{
new Integer(arg0 )});
} catch
(java.lang.reflect.InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if (th.getClass() ==
hu.capsys.wwwsol.control.WwwsolException.class){ // HERE IS THE BUG
nsafterUpcall("removePerson", delegate, th);
throw (hu.capsys.wwwsol.control.WwwsolException)th ;
nsafterUpcall("removePerson", delegate, th);
java.rmi.RemoteException subex = nsinvalidateDelegate(delegate,
th);
delegate = null;
throw subex;
catch (java.lang.Throwable ex)
nsafterUpcall("removePerson", delegate, ex);
java.rmi.RemoteException subex = nsinvalidateDelegate(delegate,
ex);
delegate = null;
throw subex;
finally
if(delegate != null)
nsreleaseDelegateForUpCall(delegate);
nsafterUpcall("removePerson", delegate, null);
}Hi,
My collegue had problems with exceptions in iPlanet EJB-s.
Exceptions that were inherited from the class that is declared to be
thrown by a particular method made EJB-s to be destroyed due to an
unhadled exception. (Eg. NoSuchObjectException is found to be unhandled
even if FinderException is declared to be thrown.)
This is a serious malfunction of the container and against the basic
concept of EJB and also the Java itself.
The root cause that were found is highlighted in the code example, where
direct equality is used for testing class instead of the instanceof
operator. This code has been found in ejb_skel_CLASSNAME.java and has
been generatd by ejbc iAS6 SP3.
Regards,
Gy�rgy Szondy
Capital Systems Kft.
Gy�rgy Szondy, Development Team Manager
Gogol u. 16., 1133 Budapest, Hungary
Tel: +36 1 288 7036 mailto:[email protected]
Fax: +36 1 350 8159
-----Eredeti �zenet-----
Felad�: Geiszter Gy�rgy
Elk�ldve: 2001.okt�ber.8. 14:23
C�mzett: Szondy Gy�rgy
T�rgy: Exception handling in EJB-s
public void removePerson(int arg0) throws java.rmi.RemoteException,
hu.capsys.wwwsol.control.WwwsolException
Object delegate = super._ns_getDelegateForUpCall();
try
nsbeforeUpcall("removePerson", delegate);
try
delegate.getClass().getMethod("removePerson", new Class[]{
Integer.TYPE}).invoke(delegate, new Object[]{
new Integer(arg0 )});
} catch
(java.lang.reflect.InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if (th.getClass() ==
hu.capsys.wwwsol.control.WwwsolException.class){ // HERE IS THE BUG
nsafterUpcall("removePerson", delegate, th);
throw (hu.capsys.wwwsol.control.WwwsolException)th ;
nsafterUpcall("removePerson", delegate, th);
java.rmi.RemoteException subex = nsinvalidateDelegate(delegate,
th);
delegate = null;
throw subex;
catch (java.lang.Throwable ex)
nsafterUpcall("removePerson", delegate, ex);
java.rmi.RemoteException subex = nsinvalidateDelegate(delegate,
ex);
delegate = null;
throw subex;
finally
if(delegate != null)
nsreleaseDelegateForUpCall(delegate);
nsafterUpcall("removePerson", delegate, null);
} -
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 -
Hello,
I have a simple CE application, which stores data in a backend system and receives a ticket number. In case an error occures, the application service implementation catches the EJBException and throws a CAFServiceException.
Unfortunately the guided procedure process finishes, even if the backend system is not available and the CAFServiceException has been thrown (I see this in the default trace).
How can I exactly show errors when finally submitting the last process step? I want to avoid finishing the process if the backend system can not process the data or is not available.
Any hint?
Cheers,
DanielHi Alexander,
[Here|Exception handling; (unfortunately not)
Regards,
Dharmi -
Customised Exception handling class.....
Hello Friends,
I am working on a project for which I need to create my own exception handling class.
The reason I need this class is to catch any exceptions and get a customised error message
according to each exception and then be able to display those messages on web page.
some examples of the exception I want to catch and display appropriate message are..
1. a duplicate reord in db
2. wrong data type (this will deal with ints,doubles and strings data types)
3. date type validation ( to make sure its date object instead of a string)
and there are several more messages but if can get some help or idea from any one to design a class for the above errors I might be able to manage other errors as well.
greatly appreciate any respnses.First off, you can extend Exception:
public class MyException extends Exception {
}You can put some custom messages into the class:
public class MyException extends Exception {
public static final String DUPLICATE_RECORD = "Duplicate record in db",
WRONG_DATA_TYPE = "Wrong data type",
VALIDATION_ERROR = "Invalid data type";
}Then, have your constructors, which take a String as an argument, so they can get your 'presets' or a custom message:
public class MyException extends Exception {
public static final String DUPLICATE_RECORD = "Duplicate record in db",
WRONG_DATA_TYPE = "Wrong data type",
VALIDATION_ERROR = "Invalid data type";
public MyException(String message) {
super(message);
}You could also have a series of exception classes: DuplicateRecordException, WrongDataTypeException, ValidationException, etc. Hope that helps.
m -
Exception handling - general concepts
ok, well i skipped the chapter on exception handling :=)
Correct me if im wrong, but lets say im writing some code and im not sure how to handle some of the exceptions that might get thrown or what exceptions will get thrown for that matter. How does one go about handling every possible exception that is "required".
I guess what im trying to ask is that if a certain block of code is calling methods that throw specific exceptions, then you will need to handle those exceptions. So that means you need to be aware of, or know to go lookup the possible exceptions that those methods can throw.
Im skipping around in Beginning Java 2, from wronx press jdk 1.4 editionThis is quite a hard one to be specific on as I think most of us learned this with a bit of trial and error.
1. IO always requires the method to be thrown ie
public void writeContents() throws IOException {
// methods
2. The compiler will tell you when you need a try /catch block
3. I often code this with;-
try {
// my methods here;
catch (Exception ignore) {}
and have empty braces with a general catch all Exception on the first run
4. Then if there are problems such as the code won't work I fill in the blanks ie;-
catch (Exception e) {System.out.println(e);}
// or e.getMessage() );
// or printStackTrace();
depending on what the first message is
5. Correct the exception now that you know what it is. Really this is a form of 'divide and conquer' as you eliminate the problems as they occur through javas exception handling abilities.
6. With a bit more practice you will implement things like finally and know when to put the handler back to 'catch (Exception ignore) {}' and when to leave it in.
7. Exception handling can also be used to instruct the client in useful ways too eg;-
try {
myTextfield.setText("Enter Your Age");
myInt = parse ...(myTextfield.getText(etc ...
catch (NumberFormatException nfe) {
myTextfield.setText("Enter Number Values Only");
// or something like
catch (NullPointerException nfe) {
myTextfield.setText("Oops you forgot to enter a value");
This has been my experience anyway + I trust I have assisted -
SIGSEGV during Exception handling in Solaris 10/Sunstudio 11
Hi all,
In our application we are encountering random crashes in our ACE/TAO framework code. The crash happens mostly when we convert our local data type to a CORBA datatype.
There is some exception handling in this area and crashes seem to happen randomly.
The stack always has a call to impl::ex_free and I saw other forums reportign this problem much earlier.
We are using a machine which has a pretty old patch for compilation. Acutally it was a Beta patch delivered for allowing clearcase installation.
The machine details are:
SunOS amsbuild8-1 5.10 ws.10.6198523 sun4u sparc SUNW,Sun-Fire-V440
The machine on which our appln runs has the details as:
SunOS sol-890perf1 5.10 Generic_127127-11 sun4u sparc SUNW,Sun-Fire-V890
What I would like to know is, has there been any known issue on Sunstudio11 related to Exception Handling in C++ and if there are any patches which came with the fix.
I know I could use the latest patches and test to see if it occurs, but it would be nice if we know our issue is the same, as we have little test time on our hands.
The stack looks like this:
f7d60a4c free (64646f36, 7a123, 136fc, 7a11b, 7a0fb, f7d74228) + 158
edb3802c __1cJ_ODI_free6Fpc_v_ (7a123, 3cc0, 21b190, eda8ca0c, edd53128, 3c00) + a0
eda8cb80 __1c2K6Fpv_v_ (7a123, 0, 0, 0, 0, 0) + 4
ed717828 __1cFCORBALstring_free6Fpc_v_ (7a123, 0, 0, 0, 0, 0) + 4
feb711a4 __1cDTAOHdetailsSstring_traits_base4Cc_Hrelease6Fpc_v_ (7a123, f7d7424c, f7d74248, 1b,
cd2f30, baddc800) + c
feb6f9f8 __1cDTAOKString_var4Cc_2T5B6M_v_ (2aef0c, ec6cdbe0, 1, 150ceb0, ff00, e9940) + 10
ed6b02d4 __1cFCORBAJException2T5B6M_v_ (2aef08, 300030, ed7a9fa8, ed799be8, 3a0, 0) + 30
ed73cb5c __1cFCORBANUserException2T5B6M_v_ (2aef08, feadff43, ed7b8c38, ed799be8, 250, 0) + 28
ec69e4a8 __1cFCORBAITypeCodeHBadKind2T6M_v_ (2aef08, 1, 2aeec0, ec69e4a4, 1, eb8fbbbc) + 4
*00235c0c __1cH__CimplHex_free6F_v_* (2b2f04, 1, 2aeec0, 298968, 62dc4, 2ff2648) + 6c
ec69d5b8 __1cFCORBAITypeCodeKequivalent6kMp1_b_ (1, ec6e2794, ec1f3700, feaf319c, 2ff2a00, eb8f
bc8c) + 218
fead7e60 __1cDTAOPAny_Dual_Impl_T4nGEvtSvcMIdlEventList__Hextract6FrknFCORBADAny_pFpv_vpn0EITyp
eCode_rpkn0C__b_ (cd2fd8, feac9710, feaf319c, eb8fbe9c, edd53128, 3c00) + 60
feacb1c4 __1c2R6FrknFCORBADAny_rpknGEvtSvcMIdlEventList__b_ (cd2fd8, eb8fbe9c, 5b524, feb6a7f4,
f1795e78, 1e39bb4) + 54
feb93a58 __1cSEvtEventDispatcherKpullEvents6Fkpkc_v_ (febc4b04, feb937c0, effecb34, effdde64, 3
78, 0) + 298
eff49698 __1cVACE_OS_Thread_AdapterGinvoke6M_pv_ (ac88d8, effee0c0, feb937c0, febc4b04, efdc0a0
0, 1) + 5c
eff06b58 ace_thread_adapter (ac88d8, eb8fc000, 0, 0, eff4963c, effee0c0) + c
Thanks in Advance,
ChenthilThere have been some exception-handling bugs fixed, most of which are in the C++ runtime library.
Be sure you have the latest runtime library patch. For Solaris 10 on sparc, that would be 119963-10.
To find out whether you have this patch, run the command
showrev -p | grep 119963and see if you have the -10 update.
I recommend upgrading to Sun Studio 12, since you are on Solaris 10. It has bug fixes and improvements not available in Studio 11. You should be able to drop in the new compiler and continue development. You don't have to rebuild all your binaries, but everyone must upgrade to the new compiler. You can download Studio 12 here:
[http://developers.sun.com/sunstudio/]
Whether you upgrade to Sun Studio 12 or stay with Studio 11, get the current patches here:
[http://developers.sun.com/sunstudio/downloads/patches/index.jsp]
(You can find the C++ runtime library patches here too.)
Finally, just because the runtime library is in the stack trace doesn't mean you have run into a bug in the library. The bug could be in your own code. For example, if you throw a deleted object, the segfault will probably occur in the runtime library when it tries to access the invalid object.
Running under dbx with RTC (run-time checking) enabled will help to find the source of the problem, especially if it is in your code. In dbx, try "help rtc" for more information, or refer to the dbx manual.
Here is a quick start guide:
% dbx myprog
(dbx) check -all
(dbx) run -
Petstore: Exception handling
Finally got a chance to go thru Petstore but got stuck on the exception handling.
HTMLOrderAction creates an instance of MissingFormDataException and stores it in the session when form data is missing. My questions:
Where is it thrown?(if ever)
Where is it caught?(if ever)
I turned off the clientside validation and got:
javax.servlet.ServletException: MainServlet: unknown exception: javax.ejb.EJBException
at com.sun.j2ee.blueprints.waf.controller.web.MainServlet.doProcess(MainServlet.java:125)
at com.sun.j2ee.blueprints.waf.controller.web.MainServlet.doPost(MainServlet.java:104)....
Shouldn't the exception be handled before it makes it to the EJB tier?
Thanks.I turned off the clientside validation and got:
javax.servlet.ServletException: MainServlet:
unknown exception: javax.ejb.EJBException
SNIP
Shouldn't the exception be handled before it makes it
to the EJB tier?Generally, all validations should be made before the EJB tier, but this is always not possible. There are specific cases when validations cannot be done without hitting the EJB tier.
This however seems to be a design issue. If the application design depends on the front-end validation, these would not be handled till the EJB tier. For a fool-proof design, there might be multiple layers of validations but they have their own issues.
These are just considerations I give while designing! Nothing in the strictest sense.
***Annie*** -
Very simple exception handling
I know next to nothing about exceptions, I am still only in 3rd week of class, but I already ran into one.
I was using the Scanner Class, and the nextInt() function (method ?) to get some numbers to do simple math on. Program worked fine. But if I put a letter in when it asks for a number, it crashs to commandline with exception error. I just added text that told the user only to put in the right var type. Integers in this case. How would I make an exception handler ? is that right, exception handler ? that would simply say "wrong data type, please reenter", then ask again ? or something ?
Getting used to the forum here, bit different than I'm used to. Hope my question was clear.ok, I scanned through all and read thoroughly some of that. I have been working my way through the series as I can. we will be covering this in some detail later in the semester. That article (chapter?) is great, but it is too broad for me right now, I will post some code, and add some comments that try to do some of what I got from that article.
This is a stupid hello world type thing idid, we had worked with Scanner nextInt(), but not Scanner next, so I looked up how to get strings on my own... first week first prog i did anything on besides follow along :)
// Java Document
import java.util.Scanner; // uses Scanner Class
public class sparkle //main method
public static void main( String args[] )
Scanner input = new Scanner( System.in );
String name;
//so here I would add a try statement ?
System.out.print( "Enter Your Name:" );
name = input.next();
// and end it here ?
System.out.printf( "%s\t%s\t%s\n\t\t%s",
"***", "Java Programming!", "***", name);
// then I would put a catch here ? that tested to see if it was a string ?
//and if not then what ?
}maybe that is a bad example... I get that you have to wrap a block of code in a try statement, then you put catch statements, that see if the can do something about watever exception it is, but what do they do, the examples in that article use stuff way past where I am now... libraries I'm not familiar with to know what is happening. What does finally do ? what should happen instead, or what should happen either way ? I will go over more of that article, but most of it is meant to be read after I am further along... I think I am getting the basics though. Do I seem to be on the right track..?
I will post some more code about this later, I really don't expect to solve this overnight, but i know good exception handling hardens a program to faults, and provides stability. So I want to get a grasp of what to expect now. really, we wont be covering this in class for another month or two... but I want to prepare now, so I will be programming well by then.
Edited by: lord_midnight on Feb 15, 2008 4:02 PM -
MC.9 and MCY1 and Exception Handling in (Logistics Inf. Sys)LIS
Hi,
I want the 'Valuated Stock Value" greater then or equal to zero (>=) appear in the MC.9 report. I can create 'Exception' in MCY1 but am unable to do so. Once I am in MCY1; I choose 'Requirements' then Key Figure 'Valuated Stock Value' then 'Type of condition' is 'Threshold Val. Anal.' is set to '> 0'. However, the report still displays zero values in MC.9. I don't want to display 'Valuated Stock Value' zero to be displayed on the report. Please help.
Thanks
NavedHey Chris,
I got the point for exception handling in weblogic 9.2. We ae using 9.2. It comes up with the concept of shared page flows which means all my unhandled exceptions are thrown to the shared page flow controller. There based on the type of exception, i can forward the request to appropraite page.
Thanks anywyas,
Saurabh
Maybe you are looking for
-
Microsoft Office Excel - compatibility Checker message in BPC 7.5
Hello Experts, We are using BPC 7.5 M with Office 2007 on Application Server, we have upgraded from BPC 5.1 with Office 2003 where Dimension were of .xls and templates & Reports were of .xlt (office 2003 format) , After upgrade we have not done any c
-
I have posted a webpage and tested the link (a movie) on a windows machine. A message came up saying that 'Quicktime is missing software required to perform this operation. Unfortunately, it is not available on the QT server.' Then it looked like it
-
Lenovo U450p Fan control Can someone modify?
Hello! i found a thread where a guy modified the Idepad 350 Bios so that the fan noise is fixed. Can someone also do this for the 450? This would be great! Many thanks!
-
Hi. I've been searching some possibilities to navigate between pages having a master-detail relationship. One possible way is to use Breadcrumbs. Very easy to implement, but not very stylish. I thought about using tabs, but, is there a way to impleme
-
Custom table entry if transaction fails
hey ppl, One doubt. I am using a exit in sales order and the requirement is that once the exit is triggered,few values must be updated on the custom table that i have created. My question s that, i am able to modify my custom table but if for some re