To signal an abnormal condition in a C# program, throw an
exception by using the throw
keyword.
The following line of code creates a new instance of System.Exception
and then throws it:
throw new System.Exception( );
Example 16-1
illustrates what happens if you throw an exception and there is no
try/catch
block to catch and handle
the exception. In this example, you’ll throw an exception even though
nothing has actually gone wrong, just to illustrate how an exception can
bring your program to a halt.
Example 16-1. Unhandled exception
using System; namespace UnhandledException { class Tester { static void Main( ) { Console.WriteLine( "Enter Main..." ); Tester t = new Tester( ); t.Run( ); Console.WriteLine( "Exit Main..." ); } public void Run( ) { Console.WriteLine( "Enter Run..." ); Func1( ); Console.WriteLine( "Exit Run..." ); } public void Func1( ) { Console.WriteLine( "Enter Func1..." ); Func2( ); Console.WriteLine( "Exit Func1..." ); } public void Func2( ) { Console.WriteLine( "Enter Func2..." ); throw new ApplicationException( ); // this next line can never execute Console.WriteLine( "Exit Func2..." ); } } }
The output looks like this:
Enter Main... Enter Run... Enter Func1... Enter Func2... Unhandled Exception: System.Exception: Exception of type System.Exception was thrown. at ExceptionHandling.Tester.Func2( ) in sourceexceptionsexceptionhandlingclass1.cs:line 34 at ExceptionHandling.Tester.Func1( ) in sourceexceptionsexceptionhandlingclass1.cs: line 27 at ExceptionHandling.Tester.Run( ) in sourceexceptionsexceptionhandlingclass1.cs: line 19 at ExceptionHandling.Tester.Main( ) in sourceexceptionsexceptionhandlingclass1.cs: line 13
When you run this code, you’ll also receive a warning that the following line is unreachable:
Console.WriteLine( "Exit Func2..." );
That’s because the compiler can tell that there’s no way this line will ever be reached. In this example, you can ignore the warning, but as noted earlier, you should usually try to write warning-free code.
This simple example writes to the console as it enters and exits
each method. Main( )
calls Run( )
, which in turn calls Func1( )
. After printing out the “Enter Func1”
message, Func1( )
immediately calls
Func2( )
. Func2( )
prints out the first message and
throws an object of type System.Exception
.
Execution immediately stops, and the CLR looks to see if there is
a handler in Func2( )
. There is not,
and so the runtime unwinds the stack (never printing the exit statement)
to Func1( )
. Again, there is no
handler, and the runtime unwinds the stack back to Main( )
. With no exception handler there, the
default handler is called, which prints the error message, and
terminates the program.