开发者

Acting on two different Exceptions in one catch block

Is there a way to catch two different exceptions and process them in one catch block in .NET?

I'm thinking of something like

try {} 
catch(OverflowException ex1, FormatException ex2) 
{
} 

I 开发者_如何学运维know I can use functions to reuse redundant logic in my catch blocks but I'm still curious as to whether a shorthand method exists for this.


No shorthand method exists. From §B.2.5 of the C# 3.0 specification, the grammar describes how a specific catch clause may only have a single class-type and an optional identifier:

try-statement:
    try   block   catch-clauses
    try   block   finally-clause
    try   block   catch-clauses   finally-clause

catch-clauses:
    specific-catch-clauses   general-catch-clauseopt
    specific-catch-clausesopt   general-catch-clause

specific-catch-clauses:
    specific-catch-clause
    specific-catch-clauses   specific-catch-clause

specific-catch-clause:
    catch   (   class-type   identifieropt   )   block

general-catch-clause:
    catch   block

Is there a reason you can't catch Exception and use that?


You could derive both OverflowException and FormatException from a common base and catch the base.

try {} 
catch(exceptionBase ex1) 
{
} 

See here for quite a bit more nuts-and-bolts information about try/catch/finally blocks.


as per my knowledge its not possible.

you can try

try {} 
catch(Exception ex) 
{
if (ex is OverflowException )
{
 //do this
}
else if(ex is FormatException )
{
 //do this
}
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜