Michael
Michael

Reputation: 13636

How to determine from where came exception?

Here is the code structre:

 try
    {
       --outter code block;

       try
         { 
            --inner code block;
         }

        catch(Exeption ex)
        {
          throw new Exception() 
          --inner catch block
        }
    }
    catch(Exeption ex) 
    {
       --outter catch block
    }    

How can I determine in outter catch block if exception generated in outter code block or throwed in inner catch block?

Upvotes: 0

Views: 48

Answers (2)

Scott Chamberlain
Scott Chamberlain

Reputation: 127603

The way you handle this is the inner code block should be including the execption in its innerException parameter if you plan on throwing a new exception or just using throw; to let the exception bubble up.

try
{
   //outter code block;

   try
     { 
        //inner code block;
     }

    catch(Exeption ex)
    {
      throw new MySpecialException("Some Extra Information", ex);
      // or
      throw;
    }
}
catch(Exeption ex) 
{
   //ex.InnerException contains the "ex" from up above if you used MySpecialException
   // or ex will be the same exception with the same stack trace if you used throw;
}  

Note, it is considered extremely bad practice to do throw new Exception you should always be throwing some more derived exception or your own user exception and that exception you throw should add some new piece of information. If you don't need to create a new exception to add more information just use the throw;

Upvotes: 3

Oswald
Oswald

Reputation: 31685

Throw exceptions of different types or pass different string arguments to the constructor.

Upvotes: 1

Related Questions