throw: Explicitly Throwing Exceptions


throw: Explicitly Throwing Exceptions

In the previous sections, we have experienced the runtime's ability to automatically throw an exception when an abnormal condition arises. With the throw keyword, you can also throw an exception explicitly in your code, as in the following line:

 throw new System.Exception(); 

This line creates and throws a new exception object of class System.Exception. You can alternatively provide a suitable string argument to the new object as follows:

 throw new System.Exception("Invalid set of parameters"); 

This string can be accessed via the exception object's Message property presented earlier.

You can only throw objects that are of class System.Exception or a subclass thereof.

An explicitly thrown exception object has the same effect on execution flow and is caught in the same way as an implicitly thrown exception object.

The syntax for throwing an exception is shown in Syntax Box 19.2.

Syntax Box 19.2 Explicitly Throwing an Exception

 throw <Exception_object>; 


You can either create a new exception object as you are throwing it:

 throw new <Exception_class_identifier> ( [<String_message>] ); 

or you can throw an exception object that has already been created:

 System.Exception myExceptionObject = new System.Exception( [<String_message>] graphics/ccc.gif ); throw myExceptionObject; 

The ability to throw exceptions explicitly not only gives you more control over when exceptions are thrown and their types, it also allows you to let inner catch blocks rethrow exceptions to outer try blocks. The inner catch block can then take initial corrective actions, followed by further actions in outer catch blocks. Listing 19.6 demonstrates how to explicitly throw and rethrow exceptions.

Listing 19.6 LogException.cs
01: using System; 02: 03: class Tester 04: { 05:     public static void Main() 06:     { 07:         try 08:         { 09:             double number; 10:             double result; 11: 12:             Console.Write("Calculate Log for the following number: "); 13:             number = Convert.ToDouble(Console.ReadLine()); 14:             result = MyMath.CalculateLog(number); 15:             Console.WriteLine("The result is: { 0} ", result); 16:         } 17:         catch(ArithmeticException exObj) 18:         { 19:             Console.WriteLine("Inside Main's catch block"); 20:             Console.WriteLine("Message: " + exObj.Message); 21:             Console.WriteLine("Help Link: " + exObj.HelpLink); 22:             Console.WriteLine("Method call trace: " + exObj.StackTrace); 23:         } 24:     } 25: } 26: 27: class MyMath 28: { 29:     public static double CalculateLog(double num) 30:     { 31:         try 32:         { 33:             if(num < 0.0) 34:             { 35:                 throw new ArithmeticException("Logarithm of a negative number cannot  graphics/ccc.gifbe calculated"); 36:             } 37:             if(num == 0.0) 38:             { 39:                 ArithmeticException arithEx = new ArithmeticException( "Logarithm of  graphics/ccc.gifzero is -infinity"); 40:                 arithEx.HelpLink = "http://www.themathwizards@#$.com"; 41:                 throw arithEx; 42:             } 43:             return Math.Log(num); 44:         } 45:         catch(ArithmeticException exObj) 46:         { 47:             Console.WriteLine("Inside CalculateLog's catch block"); 48:             throw exObj; 49:         } 50:     } 51: } 

Sample output 1:

 Calculate Log for the following number: 10<enter> The result is: 2.30258509299405 

Sample output 2:

 Calculate Log for the following number: 0<enter> Inside CalculateLog's catch block Inside Main's catch block Message: Logarithm of zero is -infinity Help Link: http://www.themathwizards@#$.com Method call trace:    at MyMath.CalculateLog(Double num)    at Tester.Main() 

Sample output 3:

 Calculate Log for the following number: -5<enter> Inside CalculateLog's catch block Inside Main's catch block Message: Logarithm of a negative number cannot be calculated Help Link: Method call trace:    at MyMath.CalculateLog(Double num)    at Tester.Main() 

The CalculateLog method in lines 29 50 calculates and returns the logarithm of a given argument. The logarithm of 0 is minus infinity, and the logarithm of a negative number is not defined. Line 35 reflects this by throwing a new exception object of type System.ArithmeticException if num is less than zero. Similarly, if num is equal to zero an exception of the same class is created and thrown in lines 39 41, albeit in a slightly different way. This time, we first create the exception object arithEx in line 39 and, before it is thrown in line 41, we assign a string value to its HelpLink property. As soon as either line 35 or line 41 is executed, the normal execution is immediately stopped. A matching catch block is found in lines 45 49 where the exception object is rethrown in line 48. Consequently, this catch block does not bring execution flow back to normal, the search for a matching catch block to this rethrown exception object continues in an outer try block instead. A match is found in Main's catch block, which accesses the Message, HelpLink, and StackTrace (providing a method call trace) properties and prints their return values on the console.

Notice how two catch blocks in this case are involved in handling one exception.


C# Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 286
Authors: Stephen Prata

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: