29

Sometimes I do this and I've seen others doing it too:

VB:

Try
    DontWannaCatchIt()
Catch
End Try

C#:

try 
{ 
    DontWannaCatchIt();
} 
catch {}

I know I should catch every important exception that I'm expecting and do something about it, but sometimes it's not important to - or am I doing something wrong?

Is this usage of the try block incorrect, and the requirement of at least one catch or finally block an indication of it?

Update:

Now I understand the reason for this, and it's that I should at least comment on the empty catch block so others understand why it's empty. I should also catch only the exceptions I'm expecting.

Luckily for me I'm coding in VB so I can write it in just one catch:

Catch ex As Exception When TypeOf ex Is IOException _
                    OrElse TypeOf ex Is ArgumentException _
                    OrElse TypeOf ex Is NotSupportedException _
                    OrElse TypeOf ex Is SecurityException _
                    OrElse TypeOf ex Is UnauthorizedAccessException
    'I don't actually care.
End Try
6
  • 1
    @asawyer No, I've already said I know I should catch every important exception, I'll make it more bold because it's not legible enough for you. Dec 27, 2010 at 16:43
  • 1
    Can you give an example where you consider an exception "not important enough to be caught"? Likely, there is your mistake.
    – peterchen
    Dec 27, 2010 at 16:48
  • 3
    @Camilo Catching every important exception is a bad idea. You only catch that which you can handle, otherwise your application should die horribly and let someone know it died so that the programmer can fix it. Dec 27, 2010 at 16:52
  • @George edited because that's still not what I've meant, my fault. Dec 27, 2010 at 17:08
  • Now that you've edited it, where is the question? Catching important errors you might encounter like IO problems you want to swallow means you need to specify them, and c# has perfectly fine syntax for this.
    – asawyer
    Dec 27, 2010 at 17:12

10 Answers 10

44

If you don't want to catch it, why are you using try in the first place?

A try statement means that you believe something can go wrong, and the catch says that you can adequately handle that which goes wrong.

So in your estimation:

try
{
    //Something that can go wrong
}
catch
{
    //An empty catch means I can handle whatever goes wrong. If a meteorite hits the
    //datacenter, I can handle it.
}

That catch swallows any exceptions that happen. Are you that confident in your code that you can handle anything that goes wrong gracefully?

The best thing to do (for both yours and your maintenance programmer's sanity) is to explicitly state that which you can handle gracefully:

try
{
    //Something that could throw MeteoriteHitDatacenterException
}
catch (MeteoriteHitDatacenterException ex)
{
    //Please log when you're just catching something. Especially if the catch statement has side effects. Trust me.
    ErrorLog.Log(ex, "Just logging so that I have something to check later on if this happens.")

}
7
  • 11
    My main point remains, if anything goes wrong with what's in the Try block, it's ok to ignore it, because it doesn't affect anything in the program's flow. It means that no matter what happens in the try block, even in the worse possibility, it won't matter to the rest of the program. Dec 27, 2010 at 16:58
  • 4
    Then your best bet is to explicitly state that you are catch (Exception){} and why you think you can handle any exception that gets thrown. I gotta tell you, if I saw that in another programmer's code, my first thought would be, "Oh Crap." Dec 27, 2010 at 17:00
  • @George I know what you mean, it does smell bad, and that's why I'm worried that this way of ignoring exceptions (when I'm fully aware of the consequences) could be wrong, so maybe the catch block is required because I should at least put comments on it. Dec 27, 2010 at 17:12
  • 1
    @Camilo: If you ever feel the need to have a catch block that is like the one I mentioned in my previous comment, then commenting that block is a must. You want to comment it with 'why' you elected to do something that is a code-smell. Dec 27, 2010 at 17:16
  • 2
    @GeorgeStocker: I gave a vote down. Coz, the OP asks, what if we want to use only TRY. Not that he likes to write try expecting an exception.
    – Jasmine
    Nov 23, 2017 at 14:56
11

No, you should not catch every important exception. It is okay to catch and ignore exceptions you don't care about, like an I/O error if there's nothing you can do to correct it and you don't want to bother reporting it to the user.

But you need to let exceptions like StackOverflowException and OutOfMemoryException propagate. Or, more commonly, NullReferenceException. These exceptions are typically errors that you did not anticipate, cannot recover from, should not recover from, and should not be suppressed.

If you want to ignore an exception then it is good to explicitly write an empty catch block in the code for that particular exception. This makes it clear exactly what exceptions you're ignoring. Ignoring exceptions very correctly is an opt-in procedure, not an opt-out one. Having an "ignore all exceptions" feature which can then be overridden to not ignore specific types would be a very bad language feature.

How do you know what types of exceptions are important and should not be caught? What if there are exceptions you don't know about? How do you know you won't end up suppressing important errors you're not familiar with?

try
{
}
// I don't care about exceptions.
catch
{
}
// Okay, well, except for system errors like out of memory or stack overflow.
// I need to let those propagate.
catch (SystemException exception)
{
    // Unless this is an I/O exception, which I don't care about.
    if (exception is IOException)
    {
        // Ignore.
    }
    else
    {
        throw;
    }
}
// Or lock recursion exceptions, whatever those are... Probably shouldn't hide those.
catch (LockRecursionException exception)
{
    throw;
}
// Or, uh, what else? What am I missing?
catch (???)
{
}
1
3

No catch or finally is invalid. Empty catch or finally is valid. Empty catch means you don't care about exceptions, you just try to do something and it doesn't matter if it doesn't work, you just want to go on. Useful in cleanup functions for example.

2
  • Empty catch or finally compiles, both in VB and C#. Maybe it shows up in something like FxCop, in which case I could configure it to ignore it. But my concern if it's bad to do so. Dec 27, 2010 at 16:41
  • 1
    An empty finally makes no sense at all, so I can imagine FxCop complaining. An empty catch is usually a deliberate decision, which FxCop shouldn't complain about.
    – fejesjoco
    Dec 27, 2010 at 16:43
2

Also if you haven't to do something about an error maybe you should specify what kind of exception the program has to ignore.

If you have to ignore every exception, I can't see why you can't use try/catch in this way.

5
  • I've already said I care about exceptions, but not every single one. And sometimes handling them is futile - let's say your app logs what it has done so far for benchmarking purposes. If by some IO reason I miss one log, I don't care. Dec 27, 2010 at 16:40
  • Well, assuming that the exception isn't important for you I think that this could be a good approach. Bear in mind that this will hide the other exceptions so if you don't care about an IOException maybe your logger throws another error that you won't see.
    – as-cii
    Dec 27, 2010 at 16:43
  • in which case I could write a catch block that catches ImportantExeption. Dec 27, 2010 at 16:49
  • Referring to the logger example maybe your implementation of it causes an OutOfMemoryException or whatever... So if you don't care about IOException insert it in an empty catch block. I think you will never be sure if every exception is useless. Again, what if logger doesn't log anything because of an hidden Exception?
    – as-cii
    Dec 27, 2010 at 16:54
  • you are right, I'll catch only exceptions I expect from now on. Dec 27, 2010 at 17:43
2

It's usually a mistake. Exceptions signal, well, exceptional behavior; when an exception is thrown it should mean that something went wrong. So to continue normal program flow as if nothing went wrong is a way of hiding an error, a form of denial. Instead, think about how your code should handle the exceptional case, and write code to make that happen. An error that propagates because you've covered it up is much harder to debug than one that surfaces immediately.

2
  • Every file IO that fails throws an exception, and that's awesome. But then I have two possibilities: it managed to save the log or it didn't. If it didn't save the log, I don't care, so why should I code anything? Besides, what can I do about a log not saving to disk? popup an error to the user? What if bothering the user is worse than not saving the log? What if it's on a server with no user? Many variables affect the possibility and advantage of doing something in the case of an exception. Dec 27, 2010 at 16:53
  • @CamiloMartin: You got big beard scares me lol
    – Jasmine
    Nov 23, 2017 at 14:57
1

It's not made easy for you to do because it's considered bad practice by the majority of developers.

What if someone later adds a method call to the body of DontWannaCatchIt() that does throw an exception worth catching, but it gets swallowed by your empty catch block? What if there are some exceptions that you actually would want to catch, but didn't realize it at the time?

If you absolutely must do this, try to be as specific as possible with the type of exception you're going to catch. If not, perhaps logging the exception is an option.

1
  • 1
    If the method is called LogBenchmark, I don't expect anyone to code a multithreaded game of life on it. Dec 27, 2010 at 16:48
1

An error exists, has been thrown, and needs to go somewhere. Normal code flow has been aborted and the fan needs cleaned.

No catch block = indeterminate state. Where should the code go? What should it do?

An empty catch block = error handled by ignoring it.

Note: VBA has a vile "On Error Continue"...

1
  • VBA is for people that On Error Continue almost all the time. Dec 27, 2010 at 17:46
0

The reason I've heard is that if your try fails for ANY reason, giving you control of the error response is highly preferable to giving the Framework control of it, i.e., yellow screen or error 500.

1
  • I'm not giving the framework control of it, an empty catch means "give me control of the error: I won't do anything about it" Dec 27, 2010 at 17:06
0

what if you write only code with try

try
{
   int j =0;
   5/j;
}

this would equivalent to write

 int j =0;
   5/j;

so writing try does not make any sense , it only increse your count of lines.

now if you write try with empty catch or finally , you are explicitley instructing runtime to behave differently.

so that' why i think empty try block is not possible.

5
  • That's the point, I'd expect just a try to mean "try with an empty catch" or "ignore errors here". Why do I need to write a catch if I'm not writing anything on the catch? Dec 27, 2010 at 17:01
  • because in that case with empty catch , your code won't throw a runtime exception and sometime you just don't know in advance that how to handel burely in future you will dout s Dec 27, 2010 at 17:23
  • @Camilo Martin: I think this falls under the "a syntax already exists, why make another" and "it's bad form and uncommon" arguments. If you mean catch everything and do nothing, say so. Unlike an if without an else, which would be the closest example to what you are saying, a try by itself isn't as obvious from the keywords what should happen. Also, unlike the if without else, a try with empty catch should not be common and is generally considered bad form, thus there is if without needing an empty else, but no try without catch or finally. Dec 27, 2010 at 17:27
  • @Gideon think about it - if you tell me "do this" it means I have to do it and failure would be unacceptable, but if you tell me "try to do this" it sounds like it would be acceptable to fail without severe consequences. IMO it is intuitive because it's what I'd expect in plain english. Dec 28, 2010 at 0:28
  • Eh... no. Let's say j was a value given by the user. If you don't want to fuss about the user inputting zero, use a try and an empty catch. If you don't put a try in there, the program will go nuts about division by zero, and will exit. Apr 2, 2014 at 18:01
0

Yes, it is incorrect. It's like goto: one per 100 KLoc is fine, but if you need many of these, you are doing it wrong.

Swallowing exceptions without any reactions is one of the worse things in error handling, and it should at least be explicit:

try  
{      
   DontWannaCatchIt(); 
}  
catch 
{
    // This exception is ignored based on Spec Ref. 7.2.a,
    // the user gets a failure report from the actual results, 
    // and diagnostic details are available in the event log (as for every exception)
} 

The further-away-look:

Error handling is an aspect: in some contexts, an error needs to be thrown and propagate up the call stack (e.g. you copy a file, copy fails).

Calling the same code in a different context might require the error to be tracked, but the operation to continue (e.g. Copying 100 files, with a log indicating which files failed).

Even in this case, an empty catch handler is wrong.

With most languages, there is no other direct implementation than to try+catch within the loop, and build the log in the catch handler. (You could build a mroe flexible mechanism, though: Have a per-call-thread handler that can either throw, or stow away the message. However, interaction with debugging tools suffers without direct language support.)


A sensible use case would be implementing a TryX() from a X(), but that would have to return the exception in question.

2
  • 2
    Beware of velociraptors. Dec 27, 2010 at 17:02
  • 1
    Reading my code, an average velociraptor gets confused by line 30.000, so the chances for any getting to line 100.000 are pretty slim.
    – peterchen
    Dec 27, 2010 at 21:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.