Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How often should I use try and catch in C#?

Tags:

c#

When writing a C# application whose #1 priority is to never crash, how often should I used a try-catch block?

Can I encapsulate all the statements in a method in try-catch blocks?

public void SomeMethod() {     try     {         // entire contents of the function         // library calls         // function calls         // variable initialization .. etc     }     catch (Exception e)     {         // recover     } } 

What are the downsides to wrapping everything in try-catch blocks?

like image 741
Justin Tanner Avatar asked Feb 02 '09 23:02

Justin Tanner


People also ask

Should you use try catch often?

You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.

Does Try Catch affect performance?

try/catch will only effect performance if an Exception is thrown (but that still isn't because of try/catch , it is because an Exception is being created). try/catch/finally does not add any additional overhead over try/catch .

How do you know when to use try catch?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.


2 Answers

The only down side is when an exception is actually thrown. There is no overhead for wrapping the code, except for when exceptions occur.

Also, you don't want to use try/catch for control flow. Consider this (bad code):

try {      FileStream fs = File.Open("somefile.txt", FileMode.Open);  } catch (Exception ex) {     MessageBox.Show("The file does not exist. Please select another file"); } 

You'll get more performance from some thing like File.Exists. such as:

if(!File.Exists("somefile.txt"))   MessageBox.Show("The file does not exist.") 

EDIT: found the MSDN direct quote:

Finding and designing away exception-heavy code can result in a decent perf win. Bear in mind that this has nothing to do with try/catch blocks: you only incur the cost when the actual exception is thrown. You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.

like image 58
scottm Avatar answered Oct 07 '22 20:10

scottm


This is a big topic. Start here for some excellent discussion of Exception handling best practices and be prepared for a religious war...

Code Analysis Team Blog

Martin Fowler - Fail Fast

MSDN on Exception Handling

Checked vs Unchecked Exceptions

My own opinion is that for the most part you use "try/finally" a lot, but "catch" very little. The problem is that if you attempt to catch and handle Exceptions in the wrong instances, you may inadvertently put your application in a bad state. As a rule, use dev and test to learn where you actually need to handle an exception. Those will be places that you can't check. i.e. you shouldn't really need to handle nullreference or filenotfound because you can proactively check for those. Only exceptions you know may happen, but you can't do anything about. Beyond that, for the sake of your data's state, let it crash.

If you are swallowing exceptions, it generally means you don't understand your program or why you are getting an exception. Catching System.Exception is the poster child of code smells...

like image 36
jlembke Avatar answered Oct 07 '22 19:10

jlembke