I have been taught for the most part to always remove try/catch/finally blocks from my code. The reason behind this always made sense to me (if your application works the way it should, you don't need to prevent errors), but at the same time there are so many things that can cause errors that aren't due to poor coding; server hiccups, graphics seem to never fail when it comes to failing out for no apparent reason, etc. I have also been told these blocks can decrease performance, nothing I've noticed personally when I used them, but I guess this could be the case. Basically what I'm getting to is; Try/Catch/Finally a bad overall idea or another one of those good in certain cases, bad when overused for poor code to keep the application afloat, good for testing/bad for production? Just wanted some input.
-
try/catch doesn't prevent errors – Steve Dec 04 '13 at 14:36
-
5Like all language features, try/catch can be used for good and bad. Generally, avoid using catch for control flow. I don't think "finally" falls into the category you speak of. It is absolutely necessary to ensure proper resource cleanup in some cases. I don't think making a blanket "don't use it" decision is wise. You'll want to evaluate every situation as to the best way to solve it. Sometimes, try/catch is an answer. – vcsjones Dec 04 '13 at 14:37
-
@BenjaminPaul The last guy I worked with. He was, believe it or not based on that response, my senior developer/manager. I was always skeptical, but had no reason to doubt the standards provided by him. >. – Volearix Dec 04 '13 at 14:37
-
@BenjaminPaul It is not efficient to use try catch blocks every where, it really decreases the performance – Shaharyar Dec 04 '13 at 14:37
-
@Shaharyar That was his arguement, but he didn't want ANY in the code. That was my real concern. – Volearix Dec 04 '13 at 14:38
-
1Please read this article: http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx – asawyer Dec 04 '13 at 14:38
-
@Shaharyar Is that true? any proof? – Sriram Sakthivel Dec 04 '13 at 14:38
-
@Shaharyar ... Obviously it's not to be used everywhere, but who gives the advice that if code is written properly its not necessary? That was my point.. although rather badly worded in my knee jerk reaction admit idly. – BenjaminPaul Dec 04 '13 at 14:39
-
@Steve I know they don't prevent errors, but they prevent an application from crashing and burning when wrapped around error prone code. – Volearix Dec 04 '13 at 14:39
-
2The rule of thumb is pretty simple... If something exception can happen, wrap it in an exception handler. Not just *catch* the exception, but meaningfully *handle* it in some way. This is all conjecture without a specific example, though. Can you update the question with a specific instance of your use of a try/catch/finally which you were told was incorrect? – David Dec 04 '13 at 14:40
-
3Example: `File.ReadAllText` throws exceptions if the file is in access - How would you handle this without try/catch? – joe Dec 04 '13 at 14:42
-
@SriramSakthivel you can check it by measuring the execution time within or without the `try/catch` block code. – Shaharyar Dec 04 '13 at 14:45
-
4@Shaharyar I'm pretty sure catch blocks have minimal performance impact (if any). Throwing exceptions is what causes a performance hit, due to the stack winding/unwinding. – dcastro Dec 04 '13 at 14:46
-
1I would happily take a small "performance hit" with a try / catch if it meant that code that could error was handled gracefully @Shaharyar – BenjaminPaul Dec 04 '13 at 15:02
5 Answers
There are situations where you can't really avoid Try/Catch
,
Consider a situation where you want the user to input some data to be entered in a database table. User's input includes primary key as well, Now if some user enters a duplicate primary key, you will get an exception. What do you want to do now ? let the system crash or handle the exception and show a user friendly message to user for inputting something different/unique.
Consider an example, Suppose you want to check if some URL is valid and available you might need some method like: (take from here)
private bool IfURLExists(string url)
{
try
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return (response.StatusCode == HttpStatusCode.OK);
}
catch //may catch specific WebException First
{
return false;
}
}
The above method would not work without try/catch
.
Another important usage of try/finally
is with using
statement, using
works with those object which implements IDisposable
interface and translates into try/finally
block so if an exception occurs it would ensure the disposal of unmanaged resource.
Generally catch only those exceptions if you want to do something useful with them, otherwise let the exception bubble up
-
1In that case the argument would be to perform error checking and ensure the key did not exist before inserting the new record. Not just waiting for the SQL exception to return. – Volearix Dec 04 '13 at 14:41
-
-
2
-
3@Volearix: Checking beforehand would be dump as it could change between checking and doing. And serializing everything so you can correctly check beforehand and be sure it won't change would be really dumb. – Ralf Dec 04 '13 at 14:44
-
2
There is absolutely nothing wrong in using try/catch/finally blocks, if they are used in a thoughtful manner.
As a developer you cannot even imagine how different from you a customer can think, or how your system is going to interact with different systems or react to inputs you didn't thought of.
The only rule is: Do not abuse.

- 2,931
- 19
- 18

- 445
- 4
- 13
-
2Actually, I'd remove the part about user input. You should not validate user input by throwing/catching exceptions - invalid input is not really _exceptional_. – dcastro Dec 04 '13 at 14:42
-
I would say that it depends on the input. In some cases you could have to parse a document that isn't well formed; user input is not only the form fields a user have to fill. – DocKuro Dec 04 '13 at 14:44
It is utterly unclear why that person wants to completely get rid of the try/catch/finally
.
I don't even understand why finally blocks comes into the picture? Without finally how'll you reliably cleanup resources?
c# language provides using
statement which is actually a syntatic-sugar implemented over try/finally
constructs, So is that wrong? or abusive? Can you implement a using block without try/finally
?
foreach
uses try/finally
, and so many places where you really need it.
Typical example: Consider "Socket Programming", How'll you avoid catching SocketException
and IOException
when dealing with sockets? Is that practical? definitely not. they should be used when you need to.
Conclusion: try/catch/finally
should be used in a way it is supposed to. You shouldn't eat exception, that doesn't mean you have to let the exception terminate your process. You'll have to handle it.

- 72,067
- 7
- 111
- 189
A basic rule is to catch exceptions when and where you can handle them. If you cannot handle them, let them through. The final handling of anything uncaught in the progress of the program might be logging and showing an error message to the user.

- 75,013
- 26
- 93
- 142
You should only catch exceptions you can deal with, others should bubble up.
You definitly must not catch exceptions like NullReferenceException
or ArgumentOutOfRangeException
. Those are bugs and catching hides those bugs in your code.
Article regarding this topic: Vexing exceptions

- 135
- 5