Solved

How to use "try-catch" to handle InvalidCastException in vb.net?

Posted on 2013-02-02
4
1,209 Views
Last Modified: 2013-02-02
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?
0
Comment
Question by:sasllc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 6

Accepted Solution

by:
esolve earned 500 total points
ID: 38846844
Yes it is that simple:

Just remember that it is important to position catch blocks with the most specific (that is, the most derived) exception types first.
Try
    'your code here

Catch cx As InvalidCastException
    'Code that handles invalidcast exception
Catch ex As Exception
    MsgBox("Can't load Web page" & vbCrLf & ex.Message)
End Try

Open in new window


http://msdn.microsoft.com/en-us/library/fk6t46tz.aspx

Also if you are using a business layer you can "bubble up" the exception from methods in that layer to the top layer. I usually use an application exception class to add more info.
Catch ex As System.Exception
   Throw New ApplicationException _
      ("You had an error in your application")
...

Open in new window


For more best practices look at this:
http://msdn.microsoft.com/en-us/library/seyhszts.aspx
0
 
LVL 3

Author Comment

by:sasllc
ID: 38846857
But instead of positioning "catch blocks with the most specific (that is, the most derived) exception types first", is it OK to have just one catch statement at the bottom of the sub, where I would put a generic error message?  Will this approach also handle any InvalidCastException that might occur within the sub?
0
 
LVL 6

Expert Comment

by:esolve
ID: 38846900
Yes the system exception will handle "ALL" exceptions. Its ok to have only one System Exception.

Try
    'your code here
Catch ex As Exception
    'code to handle any exception
End Try

Open in new window


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()

Open in new window


You can also use the Page_Error event which might be usefull for you:

http://support.microsoft.com/kb/308132
0
 
LVL 6

Expert Comment

by:esolve
ID: 38846913
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
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question