I have a C# program with multiple methods with different parameters and different return types, but most of them have a try/catch block with the same exception logic handling. There are multiple catch statement for all methods, but the logic inside them is the same for all methods.
Is there a way to create a helper method so I won't have duplicate code in the catch ?
public static async Task<long> Method1(string requestedKey)
{
try
{
//code
return value;
}
catch (Exception1 ex)
{
Exception1Handler(ex);
}
catch (Exception2 ex)
{
Exception2Handler(ex);
}
catch (Exception3 ex)
{
Exception3Handler(ex);
}
catch (Exception ex)
{
}
return 0;
}
public static async Task<T> Method2(string key, string value)
{
try
{
//code
return value;
}
catch (Exception1 ex)
{
Exception1Handler(ex);
}
catch (Exception2 ex)
{
Exception2Handler(ex);
}
catch (Exception3 ex)
{
Exception3Handler(ex);
}
catch (Exception ex)
{
}
return default(T);
}
How could I group the catch statements in a helper method, so that I do not have duplicate code?
try .. catch
blocks. Handle only exceptions you want to handle, If exceptions can happened because of user's input, do validation instead of throwing exception. Otherwise catch all of them on top layer and provide friendly message to the user. - Fabio