Now before you write off this post as being ‘just another silly request’ hear me out.
Right now in C# we can do the following
switch( someObject )
{
case Option1:
case Option2:
case Option3:
// do something
break;
case Option4:
// do something
break:
}
Allowing fall through for a switch statement is a powerful technique. It allows for multiple case statements in the same switch block to use the exact same logic, oh, and it also allows for code reduction.
Given the fact that we can do this with a switch statement why can we not do this with try-catch statements?
As an example(s) (or a suggestion of syntax) why could we not have the following
try
{
} catch ( SomeException1 ) {
} catch ( SomeException2 ) {
} catch ( SomeException3 ) {
} catch ( SomeException4 se ) {
// do something
} catch ( SomeException5 se ) {
// do something
}
OR
try
{
} catch ( SomeException1, SomeException2, SomeException3, SomeException4 se ) {
// do something
} catch ( SomeException5 se ) {
// do something
}
I know, I know you think I have lost my mind. But think about it. There are times when you want to handle multiple exception types with the exact same logic. However today when you do this you are forced to either create a helper method to handle the logic or repeat the logic over and over again. If we had the ability to allow for fall through exceptions we could reduce duplicated code and reduce code noise.
Now before you start asking questions like … let me provide some quick Q & A
Q) If you do this you will never be able to know exactly what type of exception was thrown.
A) You are correct, but in this scenario do you really care about the exception type? If you did I am going to guess you would break it out into individual catch block
Q) When would this situation actually be practical?
A) Consider this. You are creating a connection to a 3rd party resource (web service, wcf, api, etc) and that connection can throw a few different exceptions. In some cases if the expected exception is throw you want to log and maybe roll back a transaction or something. In this case i do not want to re-throw (or just let bubble up) the exception, but at the same time I do not want to duplicate my code.
So, let me have it. Tell me how dumb this is.
Tell next time,
Posted
01-20-2010 5:58 PM
by
Derik Whittaker