.NET HELP

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

Published May 16, 2023
Share:

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
}
try
{
    // Code that may generate an exception
}
catch (Exception ex)
{
    // handle the exception
}
Try
	' Code that may generate an exception
Catch ex As Exception
	' handle the exception
End Try
VB   C#

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);
}
try
{
    int result = 10/0;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}
Try
	Dim result As Integer = 10\0
Catch ex As DivideByZeroException
	Console.WriteLine("An error occurred: " & ex.Message)
End Try
VB   C#

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;
}
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);
}
try
{
    int [] numbers = new int [7];
    numbers [12] = 70;
}
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);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

In this example, the code inside the try block attempts to assign a value to an array index that doesn't exist, generating a 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);
}
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);
}
Try
	Dim result As Integer = 10 \ 0
Catch ex As DivideByZeroException When ex.Message.Contains("divide")
	Console.WriteLine("An error occurred: " & ex.Message)
Catch ex As DivideByZeroException
	Console.WriteLine("A different divide by zero error occurred: " & ex.Message)
End Try
VB   C#

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.");
}
try
{
    int result = 10 / 2;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
    Console.WriteLine("This line will always be executed.");
}
Try
	Dim result As Integer = 10 \ 2
Catch ex As DivideByZeroException
	Console.WriteLine("An error occurred: " & ex.Message)
Finally
	Console.WriteLine("This line will always be executed.")
End Try
VB   C#

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)
    {
    }
}
public class CustomException : Exception
{
    public CustomException(string errorMessage) : base(errorMessage)
    {
    }
}
Public Class CustomException
	Inherits Exception

	Public Sub New(ByVal errorMessage As String)
		MyBase.New(errorMessage)
	End Sub
End Class
VB   C#

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);
}
try
{
    throw new CustomException("This is a custom exception.");
}
catch (CustomException ex)
{
    Console.WriteLine("A custom exception occurred: " + ex.Message);
}
Try
	Throw New CustomException("This is a custom exception.")
Catch ex As CustomException
	Console.WriteLine("A custom exception occurred: " & ex.Message)
End Try
VB   C#

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:

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 IronPDF.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);
}
using IronPdf;
using System;
try
{
    var renderer = new IronPDF.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);
}
Imports IronPdf
Imports System
Try
	Dim renderer = New IronPDF.ChromePdfRenderer()
	Dim html As String = "Hello, World!"
	Dim PDF As PdfDocument = renderer.RenderHtmlAsPdf(html)
	PDF.SaveAs("output.PDF")
	Console.WriteLine("PDF created successfully.")
Catch ex As Exception
	Console.WriteLine("An unexpected error occurred: " & ex.Message)
End Try
VB   C#

In this example, the try block contains the code to create a PDF using IronPDF. If an exception occurs during the process, the catch blocks 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);
}
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);
}
Imports IronPdf
Imports System
Imports System.IO

Try
	Dim pdfPath As String = "input.PDF"
	If File.Exists(pdfPath) Then
		Dim PDF As PdfDocument = PdfDocument.FromFile(pdfPath)
		Dim extractedText As String = PDF.ExtractAllText()
		Console.WriteLine("Text extracted successfully: " & extractedText)
	Else
		Console.WriteLine("The specified PDF file does not exist.")
	End If
Catch ex As Exception
	Console.WriteLine("An unexpected error occurred: " & ex.Message)
End Try
VB   C#

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 blocks 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 $749.

< PREVIOUS
C# For Each (How IT Works For Developers)
NEXT >
C# Extension Methods (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,781,565 View Licenses >