In my current project, i am interacting with some 3rd party middleware that throws many different types of exceptions (around 10 exceptions or more).
My library that is using the 3rd party has a few methods, each one interacts with the 3rd party, however needs to be protected from the same set of 10 or more exceptions.
What i currently have is something like this in every method of my library:
try
{
// some code
}
catch (Exception1 e)
{
}
catch (Exception2 e2)
{
}
...
catch (ExceptionN eN)
{
}
The number of exceptions may increase as well.
How can i reduce the code duplication and uniformly handle all exceptions in a single place?
- suppose that the handling in each method in my code is the same.
You can either use a global exception handler, the implementation depends on your project type (ASP.net -> global.asax, WPF -> App.xaml…)
Or use something like the following :
which can be invoked the following way:
If an exception was thrown during the Console.WriteLine execution, it would then be handled by your exception handling logic
Note that the code to execute might also modify external values:
If you prefer anonymous methods: