Exception Properties

:

The System.Exception base class is the class  that is inherited by all exception classes in the .NET Framework. Therefore, the  properties of the Exception class is available to  other exception classes. The following table shows some notable properties of  the System.Exception class which is shared by all  of the other exception classes.

 Property  Description
 InnerException  Specifies the Exception instance that caused the current   exception.
 Message  Specifies the message that describes the exception.
 StackTrace  Returns a string representation of the method call stack.

Figure 1 – System.Exception Properties

The Message Property


We have seen the Message property several times. It allows you to specify an  error message which describes the Exception that was thrown. For example,  consider the following code:

int x = 1;
int y = 0;
int z;

try
{
    z = x / y;
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
Attempted to divide by zero.

We intentionally try to divide by zero so the catch  block will be executed. Note that we provide an instance of the Exception class so we can use the Message property. We then print the content of the Message property. When you run the program, an  error message will show up. Every predefined Exception  class in the .NET framework has their corresponding error message stored in the Messageproperty.

If you are throwing exceptions, then you can use the overloaded constructor  of the Exception class which accepts a string  argument that is the error message.

try
{
    if (y == 0)
    {
        throw new DivideByZeroException("You cannot divide by zero. Sorry my friend.");
    }
    else
    {
        z = x / y;
    }
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}
You cannot divide by zero. Sorry my friend.

The InnerException Property


The InnerException property of the System.Exception class is used to determine the Exception that caused the current exception. For example, suppose a programmer wants to detect if the format of  an account number is correct. The first thing to do is to convert it from string to int. If the account number cannot  be converted properly to a numerical representation, then a FormatException will be thrown. Inside the catch  block for the FormatException, you can then do  some more processing and then throw another customized exception that describes  the error more clearly. The following program shows you this example.

using System;
 
namespace InnerExceptionDemo
{
    class Program
    {
        static int ProcessAccountNumber(string accountNumber)
        {
            try
            {
                return Convert.ToInt32(accountNumber);
            }
            catch (FormatException formatException)
            {
                throw new Exception("Invalid Account Number.", formatException);
            }
        }
        static void Main(string[] args)
        {
            Console.Write("Enter an account number: ");
            string input = Console.ReadLine();
 
            try
            {
                int accountNumber = ProcessAccountNumber(input);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Current exception's message: {0}", ex.Message);
                Console.WriteLine("Inner exception's message: {0}", 
                                        ex.InnerException.Message);
            }
        }
    }
}

Example 1 – InnerException Demo

Enter an account number: abcde
Current exception's message: Invalid Account Number.
Inner exception's message: Input string was not in a correct format.

In lines 7-17, we defined a method named ProcessAccountNumber. This method accepts a string argument which is the  string input given by the user. As you can see in line 25, this method is called  and the input given by the user is passed as an argument. It is also enclosed in  a try block because it might cause an exception. After the method is called the  excecution will transfer to the first line of the ProcessAccountNumber() method.

Inside that method is yet another try…catch statement. Inside the try  block, we try to convert the string argument into an integer and return the value  if successful. If the string argument cannot be converted, then a FormatException will be thrown and the succeeding  catch block will handle it. Inside the catch block, we throw a new instance of  the Exception class and provide a more descriptive  message as the first argument, and the FormatException  instance as the second argument which indicates the inner exception. The catch block inside the calling method (Main())  will then be executed (line 27) and there, we print the message of the new Exceptionand the message of the original inner  exception that caused it by using the InnerException  property and its Message property.

The StackTrace Property


The StackTrace property of the System.Exception  class allows you to inspect which method in the method-call stack produced the  exception. This is a useful method when debugging since a method might also call  other methods which may result into errors. You might mistaken that method being  called as the culprit, but it might actually be the other methods it calls. The  StackTrace shows the method-call stack as a string representation. To  demonstrate this, the following code creates a deep method-call stack where the  final method throws an exception.

using System;
 
namespace StackTraceDemo
{
    class Program
    {
        static void Method1()
        {
            Method2();
        }
 
        static void Method2()
        {
            Method3();
        }
 
        static void Method3()
        {
            throw new Exception("Exception at Method3()");
        }
 
        static void Main(string[] args)
        {
            try
            {
                Method1();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Console.ReadKey();
            }
        }
    }
}

Example 2 – StackTrace Demo

at StackTraceDemo.Program.Method3() in C:\StackTraceDemo\Program.cs:line 19
at StackTraceDemo.Program.Method2() in C:\StackTraceDemo\Program.cs:line 14
at StackTraceDemo.Program.Method1() in C:\StackTraceDemo\Program.cs:line 9
at StackTraceDemo.Program.Main(String[] args) in C:\StackTraceDemo\Program.cs:line 26

Each line shows the method, file, and the line number where the exception was  thrown. The first entry which is Method3() is the main source of the exception.  The stack continues up to the Main() method which is the top of the method-call  stack. Please note that you must run the program in debug mode to see the  complete method-call stack.