The Exception class
Learn the Message, StackTrace and InnerException properties of Exception.
Properties of the Exception class
All exceptions derive from the System.Exception class. This class has a few useful properties: Message holds the error description, StackTrace holds the call stack, and InnerException holds the original exception if any. These make debugging inside a catch block easier.
For example, catch (Exception ex) { Console.WriteLine(ex.Message); } prints the error message. With ex.StackTrace you see where the error came from, and with ex.InnerException you reach the wrapped original error. These properties are fundamental for debugging and logging.
Finding the source with StackTrace
The StackTrace property gives the call stack from the point where the exception was thrown, as text. It shows which method and which line caused the error. It is very valuable for debugging and logging.
For example, Console.WriteLine(ex.StackTrace); prints the trace line by line. From this output you can see the source of the error and the chain of methods that triggered it. Still, showing the full trace to users in production can be a security risk; logging it is a better approach.
Wrapping with InnerException
Sometimes you want to wrap a low-level error in a higher-level exception. This lets you present a meaningful message at the upper layer without losing the original error. The InnerException property carries the wrapped original exception.
For example, throw new Exception("Data load failed", innerEx); throws a new exception that holds innerEx as its InnerException. In the catch block you can reach the original error's message via ex.InnerException.Message. This technique is common in layered architectures.
Exercise Catch the message and print it
Inside a try block, throw throw new Exception("Missing data");. In a catch (Exception ex) block, print ex.Message with Console.WriteLine.
Show example solution
Write try { throw new Exception("Missing data"); } catch (Exception ex) { Console.WriteLine(ex.Message); }
Example solution:
using System;
class Program
{
static void Main()
{
try
{
throw new Exception("Missing data");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Test yourself
-
What does ex.Message return?
Exception e = new Exception("An error occurred"); Console.WriteLine(e.Message);- "An error occurred"
- null
- "Exception"
- Throws FormatException
Show answer
"An error occurred" — Correct! Message returns the description given to the constructor.
-
Access the message
catch (Exception ex) { Console.WriteLine(____); }Show answer
catch (Exception ex) { Console.WriteLine(ex.Message); } -
Why use InnerException?
- To throw faster
- To preserve the original error
- Only for strings
- To clear the StackTrace
Show answer
To preserve the original error — Correct! InnerException preserves the original error inside the wrapping exception.