13.3 Examining System.ExceptionSince System.Exception is an important class, I shall examine some of its methods and properties [10] that all other C# exception classes will inherit. Table 13.2 shows the public properties [11] of this class.
Table 13.2. System.Exception public properties
Take particular notice of StackTrace , Message , and InnerException . These three public properties are used frequently. The values of these properties can be specified in the constructor when creating a new instance of the exception. Make use of these properties as if they are public fields of the exception object. Here is an example. 1: using System; 2: 3: class MyException:ApplicationException{ 4: public MyException(string msg):base(msg){} 5: } 6: 7: class TestClass{ 8: public static void Main(){ 9: try{ 10: TestException(); 11: } 12: catch (Exception e){ 13: Console.WriteLine("Message :"+ e.Message ); 14: Console.WriteLine("StackTrace :"+ e.StackTrace ); 15: Console.WriteLine("HelpLink :"+ e.HelpLink ); 16: Console.WriteLine("TargetSite :"+ e.TargetSite ); 17: Console.WriteLine("InnerException:"+ e.InnerException ); 18: Console.WriteLine("Source :"+ e.Source ); 19: } 20: } 21: 22: static void TestException(){ 23: MyException me = new MyException("help me!"); 24: me.HelpLink = "http://helpme.com/help"; 25: throw me; 26: } 27: } Output: c:\expt>test Message :help me! StackTrace : at TestClass.TestException() at TestClass.Main() HelpLink :http://helpme.com/help TargetSite :Void TestException() InnerException: Source :test Lines 3 “ 5 contains the code for a user -defined exception class which extends System.ApplicationException . MyException has one constructor which takes in a string (the message description of the exception) and passes the string to its superclass's constructor (using the base keyword) which also takes in a string. The output shows the InnerException property to be null (nothing is printed out). In this case, Source has the value test because I saved this source file as Test.cs , and test.exe is the assembly which I executed. Source will show the name of the application which was being executed when the exception occurred. System.Exception has three [12] important overloaded constructors. These are shown in Table 13.3.
Table 13.3. Overloaded constructors of System.Exception
|