Merging modern software development with electrons and metal
Random header image... Refresh for more!

The Case of the Disappearing Exception

I was doing some debugging recently on an inherited Visual Basic.NET codebase. Something odd was going on – the code that reads a PLC’s input was always returning True, but I could see the input changing. The problem? The original programmer, who I’ll call “Bugs Bunny”, didn’t understand exception handling at all.

The function, part of a class that communicated with a PLC, went roughly like this:

Function bubba() As Boolean
    bubba = True
    Try
        bubba = getResultFromPlc()
    Catch ex As Exception
        logException()
    End Try
End Function

Since all Exceptions are caught and not handled any Exceptions raised in bubba()’s Try block just disappear. So all the code calling bubba() has no way of knowing if there are problem (such as the PLC isn’t powered or the serial port isn’t connected) . Instead, because the return value is initially set to True (bubba = True), if an Exception occurs, bubba() always return True.

Sometimes you do need to ignore Exceptions. For example, on a maintenance screen that repeatedly reads a PLC’s inputs, it’s good to indicate if there are any problems reading the inputs, but it’s not helpful to pop up a dialog box or exit the maintenance screen. Exceptions should be ignored occasionally as needed in the calling code, not completely swallowed up in the base library code.

Another common anti-pattern in Bug’s code is:

Sub joe()
    Try
        blah()
        blahblah()
    Catch ex As Exception
        logException()
        Throw ex
    End Try
End Sub

Sub groovy()
    Try
        joe()
    Catch ex As Exception
        logException()
        Throw ex
    End Try
End Sub

What’s the point? All that happens is the exception gets logged multiple times (adding confusion to the log file), more useless code is added (making the code harder to understand), and the program runs slower (throw, catching, and re-throwing Exceptions takes time).

Tony

2 comments

1 Ulrik Hagström { 01.21.10 at 6:42 am }

Hi Tony,
I just came across your blog and I find it entertaining to read, but also interesting. Since you seem to be a friend of CANopen – visit my website and download the free-of-charge CANopen API for C# – would be since to see what you think about it, in this blog :).

Keep up the good work!

2 Tony { 01.22.10 at 6:42 pm }

I’ve added a link to your CANOpen API SDK on my CANOpen resources page. The commercial license cost is reasonable.

I probably won’t have time to look at anything for a while; I’m going to be pretty busy for a few months.

Leave a Comment