Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can use Multiple catch blocks?

What I have tried:

class student
{
try{
...
}
catch (Exception ex)
{
}
catch (Exception s)
{
}
finally()
{
}

}
Posted
Updated 14-Aug-18 18:14pm

Yes, of course you can have multiple catch blocks in C#. As of C#6 you now have exception filters (VB.NET has had these a long time). See the section "Statement-level features" here: [^].

I strongly suggest you study these Exception handling guidelines from MS: [^].

F-ES Sitecore showed you a good example here, but there's one "feature" of that example I think is not good practice: having a "generic catch-all" that is going to "swallow" any Exception type you did not catch.

imho, good practice demands that you at least log an error that you "swallow." And, imho, best practice is to "never swallow," but re-throw if you must use a "catch-all."
 
Share this answer
 
If you want to use multiple catch blocks the exception type must be different

catch (ExceptionType1 a)
{
}
catch (ExceptionType2 b)
{
}
catch (ApplicationException c)
{
}
catch (Exception d)
{
}


When an exception is thrown it will check if the exception is type ExceptionType1, and if not it will go to the next catch and so on down the list until if finds a matching type.
 
Share this answer
 
Comments
[no name] 14-Aug-18 7:32am    
How can i define and add my own Exceptions?
Dave Kreskowiak 14-Aug-18 9:53am    
You forgot to mention that catch order matters. From the documentation:
the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.
F-ES Sitecore 14-Aug-18 10:01am    
> You forgot to mention that catch order matters.

You forgot to read my answer before you commented :)
BillWoodruff 15-Aug-18 0:28am    
+4 Good answer; I've expressed my one reservation about the code in my post.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900