Lesson Sunday

When our application throws an error, the program is throwing an exception. Almost every time the compiler throws an error, it uses the term "exception." An exception occurs when we execute or interact with a program that results in the program crashing.

Exception handling refers to the act of coding a program to handle exceptions in a manner that doesn't lead to the application crashing. When an exception is thrown, we can program our application to "catch" and handle the exception appropriately. We can do this with a try/catch block.

Try/Catch Blocks


When an exception is thrown, the CLR (Common Language Runtime) automatically looks for a catch statement to handle the exception. If no catch statement is found, the exception is considered "unhandled" and the execution of the program halts. In other words, our program crashes.

We can manually add code to tell our application how to handle exceptions in try/catch blocks. The try part is where we put the code that may cause an exception. If everything is fine and no exception is thrown, the application simply moves on. If an exception is thrown, the program will automatically run the code in the catch part to handle that exception.

catch blocks can take an Exception as a parameter, which can help handle exceptions even more effectively. The Exception class has a number of useful properties:

  • Message: a short description of the exception;
  • Source: the application name;
  • StackTrace: the path to what caused the exception;
  • TargetSite: the name of the method where the exception occurred.

Example

Here's an example of how we could use a try/catch block.

DivideByZero.cs
using System;

class Program
{
  static void Main()
  {
    try
    {
      int value = 1 / int.Parse("0");
    }
    catch (Exception ex)
    {
      Console.WriteLine("Message = {0}", ex.Message);
      Console.WriteLine("Source = {0}", ex.Source);
      Console.WriteLine("StackTrace = {0}", ex.StackTrace);
      Console.WriteLine("TargetSite = {0}", ex.TargetSite);
    }
  }
}
  • This program is going to try to return the value of an integer that's divided by zero. Everything compiles as expected but when we actually try to run the program and divide by zero, an exception is thrown because it isn't possible to divide by zero.

  • Normally this exception would halt the program entirely. However, because the code throwing an exception resides in the try of our try/catch block, C# will automatically run the code within the catch portion in an attempt to gracefully handle the exception.

  • The code in catch logs details about the exception to the console instead of halting the program entirely.

Compiling and running this program would result in the following output in the console:

Message = Attempted to divide by zero.
Source = DivideByZero
StackTrace =    at Program.Main()
TargetSite = Void Main()

Note: This example is adapted from the Exception Handling Tutorial on dotnetperls. Check out dotnetperls for more code samples and explanations.

Terminology


Exception handling: The act of coding a program to handle exceptions in a manner that doesn't lead to the application crashing.

Throwing an exception: When a program crashes and has an error.

Try/catch block: Composed of two parts: try and catch. The try part is where we put the code that may cause an exception. The catch part to handles that specific exception.

Example


using System;

class Program
{
  static void Main()
  {
    try
    {
      int value = 1 / int.Parse("0");
    }
    catch (Exception ex)
    {
      Console.WriteLine("Message = {0}", ex.Message);
      Console.WriteLine("Source = {0}", ex.Source);
      Console.WriteLine("StackTrace = {0}", ex.StackTrace);
      Console.WriteLine("TargetSite = {0}", ex.TargetSite);
    }
  }
}

catch blocks can take an Exception as a parameter, which can help handle exceptions even more effectively. The Exception class has a number of useful properties:

  • Message: a short description of the exception;
  • Source: the application name;
  • StackTrace: the path to what caused the exception;
  • TargetSite: the name of the method where the exception occurred.

Lesson 6 of 12
Last updated more than 3 months ago.