C# Lesson 9: Exception Handling

Ynlay
5 min readJan 10, 2023

--

Exceptions are abnormal events or run-time errors that occur during the execution of a program. They indicate that something went wrong and the program cannot continue running normally. In C#, exceptions are represented by objects that are derived from the System.Exception class.

To handle exceptions, C# provides the try, catch, and finally keywords. You can use the try block to enclose the code that might throw an exception, and the catch block to handle the exception and provide an alternative course of action. The finally block is optional and is used to execute code regardless of whether an exception was thrown or not.

In this example, the try block attempts to divide x by y. However, since y is zero, this will cause a DivideByZeroException to be thrown. The catch block catches this exception and provides an alternative course of action by displaying an error message. The finally block is executed regardless of whether an exception was thrown or not and will be used to release any resources that were acquired in the try block or to perform any other necessary cleanup operations.

It’s also possible to have multiple catch blocks to handle different exceptions, in this way it’s possible to provide specific error messages or recovery steps for each exception type. You also can create custom exception types by inheriting from the Exception class and use it to provide a more meaningful error message for the exception.

It’s a best practice to handle exceptions as close to where they occur as possible and to avoid using exception handling as a control flow mechanism. Instead, you should use it to handle unexpected situations that may occur while your program is running.

Keep in mind that the try-catch block can be used not only to handle the exceptions in your own code, but also in any external code that you’re calling.

By learning how to handle exceptions, you can ensure that your programs run more stable and don’t crash when unexpected situations occur.

Specifc Exception Types

It’s also a good practice to use specific exception types instead of the base Exception class, this will allow you to handle different types of exceptions in different ways. For example, you can handle an IOException differently than a DivideByZeroException or a ArgumentException.

Another good practice is to log exception details somewhere, whether it’s to a file, a database or a remote server, this way you can track and diagnose errors that happen in production.

In this example, the try block attempts to divide x by y. If a DivideByZeroException is thrown, it will be caught by the first catch block, which will display an error message that informs the user that the operation cannot be performed. The second catch block catches an IOException and displays an error message that informs the user that an IO error occurred. The last catch block is a catch-all block that catches any other types of exceptions that may be thrown.

It’s a good practice to catch the most specific exception first and the catch the more generic exceptions last, so that the specific exception takes priority over the general exception.

You can also create your own custom exception types by inheriting from the Exception class, this will allow you to provide a more meaningful error message for the exception, but also it’s more specific to the error that has occurred.

Finally

It’s also important to not forget the usage of the finally block. The finally block is executed regardless of whether an exception was thrown or not and it's an ideal place for cleaning up any resources that were acquired in the try block.

When designing your code, it’s a good practice to anticipate what might go wrong and plan for it. For example, if your code reads a file, it’s a good idea to check if the file exists and is accessible before trying to read from it, that way you can avoid an exception from being thrown in the first place.

Throw

Another important concept related to exception handling is the use of the throw keyword. The throw keyword allows you to throw an exception from a method, constructor, or property. It's also used to re-throw an exception that was caught in a catch block.

When you throw an exception, the runtime will look for a catch block that can handle the exception. If no catch block is found, the exception will be propagated up the call stack until it is handled or until the program exits.

When throwing an exception, it’s good practice to provide a meaningful error message that describes the problem that occurred. The error message should also include enough information to help locate the problem in the code.

In this example, we are using the ArgumentNullException class to throw an exception and provide a meaningful error message. The first parameter is the name of the argument that is null and the second parameter is the error message.

It’s important to note that throwing exceptions can be expensive in terms of performance, as well as propagating them, so it should be avoided in performance-critical code or in cases where the expected exception rate is high.

Exercise

  1. In Visual Studio, create a new C# console application called “ExceptionHandling”.
  2. In the Main method, create a try-catch block to catch an exception when dividing a number by zero
  3. In the catch block, print a message that informs the user of the error
  4. Run the program and verify that the message is displayed when an exception occurs

In this lesson, we learned about exception handling in C#, including how to use the try-catch-finally block to handle exceptions, how to throw exceptions, and how to use specific exception types. With the skills you have learned in this lesson, you can now create your own exceptions and handle them properly to improve the stability and robustness of your C# code. Remember, log exception details and provide enough information to diagnose the problem. Happy Coding!

--

--

Ynlay

Software Developer with a Computer Science Background