Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ever okay to catch an exception and do nothing? [closed]

try
{

    CallMethod()

}
catch { }

From my experience, I generally wouldn't do this.

But if I had a piece of functionality that say, uses a 3rd party COM assembly which occasionally fails and it's actually not important enough to log it cause I'll be calling it again in a couple of seconds anyway, is it okay to do this?

If not, what alternative do I have?

like image 363
Diskdrive Avatar asked Apr 28 '11 01:04

Diskdrive


3 Answers

An empty catch block like the one shown shouldn't be used.

For example, the code in your question would also catch OutOfMemoryException, StackOverflowException, ExecutionEngineException, AccessViolationException and ThreadAbortException (though the latter would be rethrown at the end of the catch block). It would even catch objects that don't derive from System.Exception (rare, but possible in managed C++ and JavaScript...in the CLR, any object can be 'thrown', but C# limits you to Exception-derived types).

If, in your example, you're using a 3rd party COM object that occasionally fails and you don't care about these failure, you should instead catch (COMException) {}, so that other more serious failures 'bubble up' and can be logged and/or fixed.

It's important to catch only those exceptions that you can actually do something about (in this case, you're explicitly choosing to do nothing about exceptions arising from CallMethod(), and I agree that a comment should be added to indicate this design decision). By following that guidance, you're preventing other bugs and problems in either the code or the runtime environment from going unnoticed.

like image 90
M. Shawn Dillon Avatar answered Nov 03 '22 04:11

M. Shawn Dillon


Sure there are times, but they should be extremely rare.

Your best practice in those cases is to leave a comment in the catch block to make sure it's clear that it's intentionally blank.

like image 39
STW Avatar answered Nov 03 '22 02:11

STW


I would at least log the occurrence with a "Warning" or lower level in the catch block, so that you can always enable logging and see what's happening if you need too.

like image 3
Anthony Accioly Avatar answered Nov 03 '22 03:11

Anthony Accioly