Program flow after an exception is thrown in C#
Hi I'm looking at some old c# code and noticing a lot of code like this:
void SomeFunction()
{
if (key.Length != Dimensions)
{
throw new KeySizeException();
}
else
{
SomeOtherFunction();
}
}
I want to know if there can ever 开发者_运维百科be a case where the else block is even necessary? Can I safely shorten the code to this with no repercussions?
void SomeFunction()
{
if (key.Length != Dimensions)
{
throw new KeySizeException();
}
SomeOtherFunction();
}
By default the exception should throw the program flow out of this method right? But I'm just wondering if there's a way in DotNet to tweak how unhandled exceptions are um handled, that would cause the 2nd implementation to work differently from the first?
You do not need the 'else' block. It is redundant. If you use a refactoring tool like 'Reshaper' or 'JustCode' such redundant code elements are usually pointed out.
The throw
is an explicit terminal in that code block, the method call will effectively end at that point. This means the else
block is redundant and can be removed.
The two are completely equivalent.
As others have said the two pieces of code are equivalent.
I thought I'd some additional thoughts though.
Firstly, the code as shown essentially implements a wrapper method (SomeFunction) that works as a guard clause for SomeOtherFunction. I'd be wary of doing that - when your KeySizeException is caught you will not know just from the stack trace that SomeOtherFunction was involved at all. It also means that you have no visibility of this requirement of SomeOtherFunction through simple code inspection of that method.
Additionally, you might conside refectoring these types of code to .Net 4.0 Code Contracts - they could give much easier to read code.
Final thought - in cases like yours I'm sometimes tempted to leave the else. This makes it 100% clear to someone else that the if/else behaviour is intended.
In C# both works in the same way. I think you are thinking if you handle the exception (rather than throwing it), how to get rid of executing the second statement?
void SomeFunction()
{
if (key.Length != Dimensions)
{
throw new KeySizeException(); //Halt the execution of SomeFunction method
}
SomeOtherFunction();
}
If you handle and do not want to execute SomeOtherFunction, you can just return as below.
void SomeFunction()
{
if (key.Length != Dimensions)
{
HandleMyException();
return; // Returns and halt the execution of SomeFunction method.
}
SomeOtherFunction();
}
精彩评论