0 votes
by (2.0k points)

Let's say that I have code that I know will throw an exception, and for two of the types of exceptions, I want to run a piece of code. Is there a way to capture both of the exceptions to run the same piece of code without duplicating? 

For example : 

try
{
	//Do Work
} catch(FormatException ex)
{
	//Handle exception
} catch (NullReferenceException ex)
{
	//Do the same thing as above
}

So the code for handling the FormatException and NullReference exception is essentially copy and paste. And if I add more exception types it's only going to get worse.

1 Answer

0 votes
by (2.0k points)

There's really two ways to achieve this. The first way is that in early versions of C#, you could simply catch *all* exceptions and then throw the ones you don't want. For example : 

try
{
	//Do Work
} catch(Exception ex)
{
	if(ex is NullReferenceException || ex is FormatException)
	{
		//Handle exception
	}
	else 
	{
		throw; //Just throw if it's not for us. 
	}
}

It's not a bad option but maybe not the cleanest. 

However starting in C# 6, you can use the "when" keyword to specify when you should catch the exception, for example : 

try
{
	//Do Work
}
catch (Exception ex) when (ex is NullReferenceException or FormatException)
{
		//Handle exception
}

It's maybe a matter of preference but it saves you a big if/else statement and rethrowing all together. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...