Example of chained exceptions stack
I do not know much about these technologies, and was not very 开发者_开发技巧successful at finding how an exception stack is displayed.
Therefore, several basic questions:
- how are 2 independent successive exceptions shown?
- how are several chained exceptions displayed?
- is the root cause displayed at the top or the bottom of the stack?
It's pretty easy to try this for yourself. For example:
using System;
class Test
{
static void Main(string[] args)
{
try
{
Top();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
static void Top()
{
try
{
Middle();
}
catch (Exception e)
{
throw new Exception("Exception from top", e);
}
}
static void Middle()
{
try
{
Bottom();
}
catch (Exception e)
{
throw new Exception("Exception from middle", e);
}
}
static void Bottom()
{
throw new Exception("Exception from bottom");
}
}
Results (the first two lines would be on one line if it were long enough):
System.Exception: Exception from top ---> System.Exception: Exception from middle
---> System.Exception: Exception from bottom
at Test.Bottom() in c:\Users\Jon\Test\Test.cs:line 43
at Test.Middle() in c:\Users\Jon\Test\Test.cs:line 33
--- End of inner exception stack trace ---
at Test.Middle() in c:\Users\Jon\Test\Test.cs:line 37
at Test.Top() in c:\Users\Jon\Test\Test.cs:line 21
--- End of inner exception stack trace ---
at Test.Top() in c:\Users\Jon\Test\Test.cs:line 25
at Test.Main(String[] args) in c:\Users\Jon\Test\Test.cs:line 9
When two independent successive exceptions are thrown, the first one will interrupt the normal execution of the program, until it is handled. Then, the second exception will be thrown in the same way, if the program was not terminated by the first one.
As for chained exceptions, you will see the last thrown exception, but that last exception was thrown when handling another exception and so forth. For example:
void Foo()
{
throw new FooException("foo");
}
void Bar()
{
try
{
Foo();
}
catch(FooException ex)
{
throw new BarException("bar", /* innerException = */ ex);
}
}
So at the top of the stack you will see BarException and at the bottom, the FooException. Hope I did not miss anything.
精彩评论