C# / Exception Handling in C#

Understanding C# Exceptions

This tutorial will introduce you to the concept of exceptions in C#. An exception is an error that occurs during the execution of a program and disrupts its normal flow. Understan…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers exception handling techniques for error management in C#.

Understanding C# Exceptions

1. Introduction

1.1 Brief Explanation of the Tutorial's Goal

This tutorial aims to introduce you to the concept of exceptions in C#. An exception is an error that occurs during the execution of a program and disrupts its normal flow. By the end of this tutorial, you should have a clear understanding of what exceptions are, how to handle them, and the best practices for exception handling in C#.

1.2 What the User Will Learn

  • What is an Exception?
  • How to handle Exceptions using try-catch blocks.
  • Using the finally block in exception handling.
  • Different types of Exceptions in C#.
  • How to create custom Exceptions.

1.3 Prerequisites

Before you start, you should have a basic understanding of C# programming, including variables, data types, control structures, and functions/methods.

2. Step-by-Step Guide

2.1 Exception Handling in C

In C#, the primary method of handling exceptions is through the use of try-catch blocks. When the code within a try block throws an exception, the execution is transferred to the appropriate catch block where the exception can be handled.

2.2 The Try-Catch Block

A try-catch block is written as follows:

try
{
    // Code that might throw an exception.
}
catch (ExceptionType ex)
{
    // Code to handle the exception.
}

Where ExceptionType is the type of exception you want to catch, and ex is a variable to hold the exception object.

2.3 The Finally Block

The finally block is used to execute code, whether an exception is thrown or not. It is often used for cleanup activities, such as closing files or releasing resources.

try
{
    // Code that might throw an exception.
}
catch (ExceptionType ex)
{
    // Code to handle the exception.
}
finally
{
    // Code to be executed regardless of whether an exception occurs or not.
}

3. Code Examples

3.1 Basic Try-Catch Example

Here's an example of a try-catch block in action:

try
{
    int[] numbers = new int[5];
    numbers[6] = 9;   // This code throws an IndexOutOfRangeException.
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine(ex.Message);
}

In this code, we're trying to assign a value to an index that doesn't exist in the array, which throws an IndexOutOfRangeException. The catch block catches this exception and prints the exception message to the console.

3.2 Try-Catch-Finally Example

Here's an example that includes a finally block:

StreamReader reader = null;
try
{
    reader = new StreamReader("nonexistent_file.txt");
    Console.WriteLine(reader.ReadToEnd());
}
catch (FileNotFoundException ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    if (reader != null)
        reader.Close();
}

In this example, we're trying to open and read a file that doesn't exist. This throws a FileNotFoundException which is caught and handled. The finally block ensures that the StreamReader is closed, even if an exception is thrown.

4. Summary

In this tutorial, we've covered:
- What exceptions are and how they disrupt program flow.
- How to handle exceptions using try-catch blocks.
- The use of finally block for cleanup activities.
- Examples of exception handling in C#.

The next step is to learn about different types of exceptions that are built into the .NET framework and how to create and use custom exceptions. You can find more information in the Microsoft Documentation.

5. Practice Exercises

  1. Write a program that catches a DivideByZeroException. Try dividing a number by zero in a try block and catch the exception in a catch block. Print the exception message to the console.

  2. Write a program that opens a file using a StreamReader in a try block. In a catch block, catch the FileNotFoundException and print the exception message to the console. Use a finally block to close the StreamReader.

  3. Write a program that catches multiple types of exceptions. In the try block, write code that could throw more than one type of exception. Have separate catch blocks for each type of exception.

Solutions

  1. DivideByZeroException
    csharp try { int result = 10 / 0; } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); }
    This code attempts to divide a number by zero, which throws a DivideByZeroException. The catch block catches this exception and prints the exception message.

  2. FileNotFoundException
    csharp StreamReader reader = null; try { reader = new StreamReader("nonexistent_file.txt"); Console.WriteLine(reader.ReadToEnd()); } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); } finally { if (reader != null) reader.Close(); }
    This code is similar to the try-catch-finally example above. It tries to open a nonexistent file, catches the resulting FileNotFoundException, and ensures the StreamReader is closed with a finally block.

  3. Multiple Exceptions
    csharp try { int[] numbers = new int[5]; numbers[6] = 9; // Throws IndexOutOfRangeException. int result = 10 / 0; // Throws DivideByZeroException. } catch (IndexOutOfRangeException ex) { Console.WriteLine(ex.Message); } catch (DivideByZeroException ex) { Console.WriteLine(ex.Message); }
    This code includes two lines that each throw a different type of exception. There are two catch blocks, each designed to catch and handle a different type of exception.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Scientific Calculator

Perform advanced math operations.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help