Catch Block Code

I have a VB.Net application which is slowly being converted to use classes rather than subs on every form.

Each form has its own, sometimes many Try, Catch, Finally blocks.

In the main the Catch blocks are the same, as are the Finally blocks.

Can I move the Catch Blocks code to an "error handling class"?

If so, how do I handle the Catch declaration? Typically  Catch sqlex As SqlClient.SqlException

Who is Participating?
käµfm³d 👽Connect With a Mentor Commented:
I'm not sure what state you would want to maintain within a logging class, so I would surmise that such a class would be Shared (a.k.a. static). If you created such a class, then you would simply need to create a method that has the appropriate signature.


Public Shared Class Logger
    Public Shared Sub LogException(ByVal sqlEx As SqlClient.SqlException)
        // log the exception
    End Sub
End Class

Open in new window

And then you would simply refer to that in your Catch block:


    // do something
Catch ex As SqlClient.SqlException
End Try

Open in new window

Since the LogException method above is defined as Shared, you use the class name (Logger) instead of an instance variable when you call the method.
käµfm³d 👽Commented:
A Catch block has to be attached to a Try block--you cannot detach it. You could, though, create a class that you use to log details of the exception, or alert someone that there was a problem.
Paul-BrooksAuthor Commented:
Thanks for responding.

I wasn't thinking about detaching it but I did have in mind to create a class to log the exceptions.

When I tried it I had an error with "sqlex" being undeclared in my class because it is declared in the Catch statement thus ....

Catch sqlex As SqlClient.SqlException

How do I declare in the Catch statement then use it in my error class?
Paul-BrooksAuthor Commented:
Thanks - that looks like the kind of thing I think I need.

I'll give it  ago now.
Paul-BrooksAuthor Commented:
Just what I needed, perfect.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.