Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling in C#: Multple Try/Catches vs. One

Tags:

c#

exception

Is it good practice to have more than one try{} catch{} statement per method?

like image 897
Miyagi Coder Avatar asked Nov 26 '22 21:11

Miyagi Coder


2 Answers

In my point of view it is good practice to have each method handle only a single task. As such you'll rarely need to have multiple try/catch blocks within a single method. However, I don't see any problems with it.

As Lisa pointed out you should catch specific exceptions and only catch the exceptions the method can actually handle.

like image 59
Brian Rasmussen Avatar answered Nov 29 '22 12:11

Brian Rasmussen


If you know the type of Exceptions that could occur beforehand, you can have a single try and catch each of those exceptions, should you want to handle them differently. For example:

try
{
    // a bunch of risky code
}
catch (SpecificException1 ex1)
{
     // handle Specific Exception 1
}
catch (SpecificException2 ex2)
{
     // handle Specific Exception 2
}
catch (SpecificException3 ex3)
{
     // handle Specific Exception 3
}
catch (Exception ex)
{
     // handle an exception that isn't specific
}
like image 31
Bullines Avatar answered Nov 29 '22 12:11

Bullines