Beware the try/catch Block that Goes to Nowhere
I was looking at a problem today and saw a code snippet that looked a lot like this:
try { if (timeToDoA) { ... } else if (timeToDoB) { ... } else { ... } } catch (Exception & e) { } catch (...) { }
where there were several if-then clauses each trying to determine what needed to be done based on the input conditions. Standard stuff.
Except for that try/catch block. That wasn't right at all.
While it was nice that the try/catch block was there to catch exceptions, I realized that it wasn't doing anything with them. This was most likely someone else in the group who put this in - if for no other reason than that's not how I would have structured it. In the end, I had something like:
if (timeToDoA) { try { ... } catch (Exception & e) { // log error about doing 'A' with exception } catch (...) { // log error about doing 'A' with unknown exception } } else if (timeToDoB) { try { ... } catch (Exception & e) { // log error about doing 'B' with exception } catch (...) { // log error about doing 'B' with unknown exception } } else { try { ... } catch (Exception & e) { // log error about doing 'C' with exception } catch (...) { // log error about doing 'C' with unknown exception } }
With this approach, I get the logging and proper error handling with the focus on the events that precipitated the exception(s) in the first place. This level of logging might seem a bit much, but if there is a section of code that's too broad and an exception is thrown, it's going to be very difficult to find what exactly caused it. Better to invest the time and keep things tight and contained rather than too loose. Certainly in this codebase.
So watch out for those try/catch blocks that go nowhere. You may bot get an exception, but you may and not know it.