Reputation: 4160
Let's say I have to catch 3 different exceptions, so I write 3 separate catch blocks. But I want to skip the finally block for one specific exception.
As far as I know this is not possible using a builtin flag. But can you advise how to solve this coding problem in elegant way?
When not using finally, I have to rewrite the same code several times, in try and also in other catch blocks.
More information:
In finally I let the thread sleep for some time (await Task.Delay(5 * 1000);
)
But if I receive a OperationCanceledException
then I don't want the finally to be run. I want it to break as fast as possible.
while (true)
{
try
{
_cts.Token.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
break;
}
catch (CustomException1 e)
{
}
catch (CustomException2 e)
{
}
finally
{
await Task.Delay(5 * 1000);
}
}
Upvotes: 7
Views: 3669
Reputation: 37000
Seems like you could use an exception-filter to filter all exceptions that should have some tidy-up-code and one single exception that doesn´t.
try
{
DoSomething();
}
catch(Exception e) when (e is MyException || e is AnotherException)
{
// your error-handling
// ...
await Task.Delay(5 * 1000);
}
catch(SpecificExceptionWithoutFinally e)
{
...
}
Before C#6 you could also introduce some flag indicating if the code should be executed:
var executeFinally = false;
try
{
DoSomething();
}
catch(MyException e)
{
executeFinally = true;
}
catch(AnotherExceptione)
{
executeFinally = true;
}
catch(SpecificExceptionWithoutFinally e)
{
...
}
finally
{
if(executeFinally) {
await Task.Delay(5 * 1000);
}
}
Anyway, this seems like a weird requirement, as the whole point of a finally
is to be guaranteed to always run regardless on any exception being thrown.
Upvotes: 2
Reputation: 2639
Do nothing in the finally block if nothing is to be done
bool skipFinallyFlag = false;
try
{
//My stuff
}
catch(Exception1 ex1)
{
//Do something
}
catch(Exception2 ex2)
{
//Do something
}
catch(Exception3 ex3)
{
skipFinallyFlag = true;
}
finally
{
if(!skipFinallyFlag)
{
//Do something
}
}
Upvotes: 12