Wow, I just got back a huge project in C# from outsourced developers and while going through my code review my analysis tool revealed bunches of what it considered bad stuff
The following only applies to languages that have checked exceptions, e.g. Java:
Sometimes a method throws a checked Exception that you know won't happen, e.g. some java APIs expect an encoding name as a string and throw a UnsupportedEncodingException if the given encoding isn't supported. But usually i pass a literal "UTF-8" that i know is supported so I could theoretically write an empty catch there.
Instead of doing that (empty catch) I usually throw a generic unchecked exception wrapping the "impossible" exception, or I even declare a class ImpossibleException that i throw. Because my theory about that error condition being impossible might be wrong and in that case I wouldn't want the exception to be swallowed.
It depends on the framework. Badly implemented frameworks might actually require this. I recall a hack in VB6 where there was no way to determine whether a collection contained an element. The only way was to try to retrieve the element and swallow the error.
To take an example from the Java world where it's OK to ignore an exception:
String foo="foobar";
byte[] foobytes;
try
{
foobytes=foo.getBytes("UTF-8");
}
catch (UnsupportedEncodingException uee)
{
// This is guaranteed by the Java Language Specification not to occur,
// since every Java implementation is required to support UTF-8.
}
That said, even in situations like this, I'll often instead use
...
catch (UnsupportedEncodingException uee)
{
// This is guaranteed by the Java Language Specification not to occur,
// since every Java implementation is required to support UTF-8.
uee.printStackTrace();
}
If the virtual machine is going to be mad/spec-breaking, there's little I can do about it, but with the stack trace, I at least get to notice when it started its descent into madness...
When it comes to Exceptions, there are always exceptions.
We have an application that does a lot of processing on behalf of other applications, where you insert some job (collection of config) into a database and the app will take it and run it at the appropriate time. We tend to swallow a lot of exceptions in that application, because even if Job1 dies in a horrifying fashion with a catastrophic error, we want the app to stay alive to take a stab at processing Job2.
I don't catch exceptions unless I plan to do something about them. Ignoring them isn't doing something about them.