Click here to Skip to main content
15,915,328 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
Nested Try & Catch possible in c#..?
Posted
Comments
jerrykid 13-Jan-11 5:19am    
you mean multi-catch?
Thomas Krojer 13-Jan-11 5:36am    
instead of asking this question please try it ....

Yes check here[^]
 
Share this answer
 
Yes
try
{
 try
 {
  ...
 }
 catch(ArgumentException aexc)
 {
  ...
 }
 ...
 // other code
 ... 
}
catch(Exception exc)
{
 ..
}


works well

Regards
Espen Harlinn
 
Share this answer
 
Comments
Ankur\m/ 13-Jan-11 5:27am    
But is it not as good as writing below code?
try
{
}
catch(ArgumentException aexec)
{
}
catch(Exception exc)
{
}
Espen Harlinn 13-Jan-11 5:40am    
OP asked about nested try/catch - and while you example is an excellent way to handle multiple exception types, you can not have a block of code between the catch statements. Point: It's not the same thing, and both have its uses.
Ankur\m/ 13-Jan-11 5:48am    
Thanks for the reply. AFAIK nested try catch is not a good practice. I would rather use a method for internal try-catch part and call the method there.

I do not doubt that your answer is correct and to the point to the question but all I was saying is you should have also mentioned about the best practice thing.
Cheers!
Espen Harlinn 13-Jan-11 6:35am    
ahh, well, best practice ... why not say fashionable? It is after all closer to the truth :) It's like common sense, it isn't common ...
Member 9394382 6-Sep-12 10:10am    
but,in nested try i want to terminate the application when the first exception occurs, but when the first exception occurs the application is not terminating.
could you please give me the solution to this
If you mean like:

C#
try
{
    // Do some work...

    try
    {
        // Do some work...

    }
    catch (Exception)
    {
        throw;
    }
}
catch (Exception)
{
    throw;
}


Then, yes, you can though I'd look very deeply at your design: this is not good practice.
 
Share this answer
 
Whatever you mean, it's probably explained in this article ;)
Using Try... Catch..., Finally![^]
 
Share this answer
 

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