IRONSOFTWAREHOME
.NET HELP

Try/Catch in C# (How It Works For Developers)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: April 23, 2026

If you're new to programming in C#, you might have heard the term "try catch" statement thrown around quite a bit. In this tutorial, we'll delve into the world of exception handling, focusing on catch blocks, and explore how you can use try and catch statements to make your code more resilient to errors. Along the way, we'll provide plenty of real-life examples to help solidify your understanding.

What are Exceptions, and Why Handle Them?

In C#, an exception represents an occurrence that takes place while a program is running, which interferes with the program's standard progression of executing instructions. When an exception occurs, the program's flow is diverted, and if the exception isn't handled, the program will terminate abruptly.

Exception handling is a way to anticipate and manage these disruptive events, allowing your program to recover from unexpected issues and continue running as intended. By using try and catch blocks, you can ensure that your code gracefully handles errors and provides users with meaningful feedback.

The Try Block

A try block is a code segment that you expect might generate exceptions. When you wrap your code in a try block, you're telling the compiler that you want to handle potential exceptions that may arise within that block.

Here's a basic example of how to use a try block:

try
{
    // Code that may generate an exception
}
catch (Exception ex)
{
    // Handle the exception
}

Catch Block Catching Exceptions

The catch statement is used in conjunction with a try block to handle exceptions. When an exception occurs within a try block, the program execution jumps to the appropriate catch block, where you can specify what the program should do in response to the exception.

To catch an exception, you need to create a catch block immediately after the try block. A catch block typically includes a parameter that represents the caught exception.

Here's an example of a catch statement in action:

try
{
    int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}

In this example, the code inside the try block attempts to divide by zero, which will generate a DivideByZeroException. The catch block then handles the exception, displaying a message to the user.

Multiple Catch Blocks Handling Different Exceptions

Sometimes, your try block might generate different types of possible exceptions. In such cases, you can use multiple catch blocks to handle each exception type separately.

The following example demonstrates the use of multiple catch blocks:

try
{
    int[] numbers = new int[7];
    numbers[12] = 70; // This line will throw an exception
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("An index out of range error occurred: " + ex.Message);
}
catch (Exception e)
{
    Console.WriteLine("An unexpected error occurred: " + e.Message);
}

In this example, the code inside the try block attempts to assign a value to an array index that doesn't exist, generating an IndexOutOfRangeException. The first catch block handles this specific exception, while the second catch block catches any other exception that might occur.

Remember, when using multiple catch blocks, always order them from the most specific to the most general exception types.

Exception Filters Adding Conditions to Catch Blocks

Exception filters allow you to add conditions to catch blocks, enabling you to catch exceptions only if a certain condition is met. To use an exception filter, add the when keyword followed by a condition in your catch statement.

The following example demonstrates the use of exception filters:

try
{
    int result = 10 / 0;
}
catch (DivideByZeroException ex) when (ex.Message.Contains("divide"))
{
    Console.WriteLine("An error occurred: " + ex.Message);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("A different divide by zero error occurred: " + ex.Message);
}

In the above example, the first catch block will handle the DivideByZeroException only if the exception message contains the word "divide". If the condition is not met, the second catch block will handle the exception.

The Finally Block Ensures Code Execution

In some cases, you might want to ensure that a particular piece of code is executed, whether an exception occurs or not. To achieve this, you can use a finally block.

A finally block is placed after the try and catch blocks and is always executed, regardless of whether an exception occurs.

Here's an example that demonstrates the use of a finally block:

try
{
    int result = 10 / 2;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
    Console.WriteLine("This line will always be executed.");
}

In the above example, even if the code within the try block doesn't generate an exception, the finally block will still be executed.

Custom Exceptions: Tailoring Exceptions to Your Needs

Sometimes, you might want to create your own custom exceptions to handle specific exceptions in your code. To do this, you can create a new class that inherits from the Exception class.

Here's an example of creating a custom exception:

public class CustomException : Exception
{
    public CustomException(string errorMessage) : base(errorMessage)
    {
    }
}

Now, you can use this custom exception in your try and catch blocks, like this:

try
{
    throw new CustomException("This is a custom exception.");
}
catch (CustomException ex)
{
    Console.WriteLine("A custom exception occurred: " + ex.Message);
}

In this example, the try block throws a CustomException instance, which is then caught and handled by the catch block.

IronPDF: Integrating PDF Functionality with Exception Handling

Learn More About IronPDF is a popular library for creating, editing, and extracting content from PDF files in C#. In this section, we'll explore how you can integrate IronPDF with your try-catch exception handling approach to handle potential errors gracefully.

Installing IronPDF

To get started, you'll first need to install the IronPDF NuGet package. You can do this using the Package Manager Console:

PM > Install-Package IronPdf

Or, you can search for "IronPDF" in the "Manage NuGet Packages" dialog in Visual Studio.

Creating a PDF with IronPDF and Handling Exceptions

Let's say you want to create a PDF file from an HTML string with IronPDF. Since the process of creating a PDF can potentially raise exceptions, you can use try-catch blocks to handle them. Here's an example of how you can create a PDF using IronPDF and handle exceptions with try-catch:

using IronPdf;
using System;

try
{
    var renderer = new ChromePdfRenderer();
    string html = "Hello, World!";
    PdfDocument PDF = renderer.RenderHtmlAsPdf(html);
    PDF.SaveAs("output.PDF");
    Console.WriteLine("PDF created successfully.");
}
catch (Exception ex)
{
    Console.WriteLine("An unexpected error occurred: " + ex.Message);
}

In this example, the try block contains the code to create a PDF using IronPDF. If an exception occurs during the process, the catch block will handle the error, displaying a relevant error message to the user.

Extracting Text from a PDF and Handling Exceptions

You might also want to extract text from a PDF file using IronPDF. As with the previous example, you can use try-catch blocks to handle potential exceptions.

Here's an example of extracting text from a PDF file using IronPDF and handling exceptions:

using IronPdf;
using System;
using System.IO;

try
{
    string pdfPath = "input.PDF";
    if (File.Exists(pdfPath))
    {
        PdfDocument PDF = PdfDocument.FromFile(pdfPath);
        string extractedText = PDF.ExtractAllText();
        Console.WriteLine("Text extracted successfully: " + extractedText);
    }
    else
    {
        Console.WriteLine("The specified PDF file does not exist.");
    }
}
catch (Exception ex)
{
    Console.WriteLine("An unexpected error occurred: " + ex.Message);
}

Try/Catch in C# (How It Works For Developers) Figure 1

In this example, the try block contains the code to extract text from a PDF using IronPDF. If an exception occurs during the process, the catch block will handle the error, displaying a relevant message to the user.

Conclusion

By combining IronPDF with your try-catch exception handling approach, you can create robust applications that gracefully handle errors when working with PDF files. This not only improves the stability of your applications but also enhances the overall user experience.

Remember to always consider potential exceptions when working with external libraries like IronPDF, and handle them appropriately using try and catch statements. This way, you can ensure that your applications are resilient and user-friendly, even when dealing with unexpected issues.

IronPDF offers a free trial of its library, allowing you to explore its capabilities without any commitment. If you decide to continue using IronPDF after the trial period, licensing starts from $999.

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

OR
bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronPdf"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

or download Windows Installer here.

  1. Download and unzip IronPDF to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronPdf.dll"

Licenses from $999