Goro Goro - 3 months ago 16
Vb.net Question

Are nested Try/Catch blocks a bad idea?

Let's say we have a structure like so:

Try
' Outer try code, that can fail with more generic conditions,
' that I know less about and might not be able to handle

Try
' Inner try code, that can fail with more specific conditions,
' that I probably know more about, and are likely to handle appropriately
Catch innerEx as Exception
' Handle the inner exception
End Try

Catch outerEx as Exception
' Handle outer exception
End Try


I have seen some opinions that nesting
Try
blocks like this is discouraged, but I could not find any specific reasons.

Is this bad code? If so, why?

Answer

There are certain circumstances where they're a good idea, e.g. one try/catch for the whole method and another inside a loop as you want to handle the exception and continue processing the rest of a collection.

Really the only reason to do it is if you want to skip the bit that errored and carry on, instead of unwinding the stack and losing context. Opening multiple files in an editor is a good example.

That said, exceptions should be just that - exceptional. A program should handle them but try to avoid them as part of normal execution flow. They're computationally expensive in most languages (python being a notable exception).

One other technique which can be useful is catching specific exception types...

Try
    'Some code to read from a file

Catch ex as IOException
    'Handle file access issues (possibly silently depending on usage)
Catch ex as Exception
    'Handle all other exceptions or just re-throw as you're unlikely to know what to do
    Throw
End Try

As pointed out by Gooch in the comments below, we also use nested try/catches in our error handling routines...

    Try
        Try
            'Log to database
        Catch ex As Exception
            'Do nothing
        End Try

        Try
            'Log to file
        Catch ex As Exception
            'Do nothing
        End Try
    Catch ex As Exception
        'Give up and go home
    End Try
Comments