sasllc
asked on
How to use "try-catch" to handle InvalidCastException in vb.net?
Our app is failing intermittently at the customer site with an InvalidCastException. There are reasons why it is very difficult to determine exactly why it is happening, and in which line of code, but the error text does show me which sub it failed in.
That sub has several if-then sections, and I feel sure the runtime problem is occuring in one of those sections. So here is my question: Can I simply put a Try statement at the top of the sub, and the Catch statement at the bottom of the sub, and expect it to handle whatever is going wrong--without erroring out of the program? Is it that simple, or are there other considerations in a situation like this?
That sub has several if-then sections, and I feel sure the runtime problem is occuring in one of those sections. So here is my question: Can I simply put a Try statement at the top of the sub, and the Catch statement at the bottom of the sub, and expect it to handle whatever is going wrong--without erroring out of the program? Is it that simple, or are there other considerations in a situation like this?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Yes the system exception will handle "ALL" exceptions. Its ok to have only one System Exception.
For ASP.NET:
Another advantage of asp.net is that it has an Application_Error event in the Global.asax file. All errors not handled will be redirected here.
You can also use the Page_Error event which might be usefull for you:
http://support.microsoft.com/kb/308132
Try
'your code here
Catch ex As Exception
'code to handle any exception
End Try
For ASP.NET:
Another advantage of asp.net is that it has an Application_Error event in the Global.asax file. All errors not handled will be redirected here.
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = "Error Caught in Application_Error event" & _
System.Environment.NewLine & _
"Error in: " & Request.Url.ToString() & _
System.Environment.NewLine & _
"Error Message: " & objErr.Message.ToString() & _
System.Environment.NewLine & _
"Stack Trace:" & objErr.StackTrace.ToString()
EventLog.WriteEntry("Sample_WebApp", err, EventLogEntryType.Error)
Server.ClearError()
You can also use the Page_Error event which might be usefull for you:
http://support.microsoft.com/kb/308132
I can also recommend the Microsoft Enterprise Library for implementing the "Exception Handling Application Block". We've been using this for the last 10 years for both Windows applications and Web Applications
http://msdn.microsoft.com/en-us/library/ff664698(v=pandp.50).aspx
http://msdn.microsoft.com/en-us/library/ff632023.aspx
http://msdn.microsoft.com/en-us/library/ff664698(v=pandp.50).aspx
http://msdn.microsoft.com/en-us/library/ff632023.aspx
ASKER