How to Catch Multiple Exceptions in C#

Here's a technique for catching more than one exception in a try / catch block.  Typically it's best to only catch the exceptions that your code can handle, so catching the general System.Exception class is discouraged.  But in this case, we're catching the general Exception class only to determine what type of exception it is.  For any exceptions that aren't handled in the if / else if blocks, we'll re-throw the exception for the calling method to handle.

catch (Exception exception)
{
	if (exception is FileNotFoundException)
	{
		Console.WriteLine("Error: File not found");
	}
	else if (exception is ArgumentException || exception is ArgumentNullException || exception is DirectoryNotFoundException)
	{
		Console.WriteLine("Error: Path is invalid or does not exist");
	}
	else
	{
		throw;
	}
}

The entire console application (Program.cs):

// Code from www.jaypm.com
// Feel free to use, but please give credit where it's due.

using System;
using System.IO;

namespace MultipleExceptionHandler
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (var fileReader = new StreamReader("file.txt"))
                {
                    while (fileReader.Peek() > 0)
                    {
                        Console.WriteLine(fileReader.ReadLine());
                    }
                }
            }
            catch (Exception exception)
            {
                // Check if it's one of three different exceptions:
                if (exception is ArgumentException || exception is ArgumentNullException || exception is DirectoryNotFoundException)
                {
                    Console.WriteLine("Error: Path is invalid or does not exist");
                }
                // Otherwise check if it's another exception:
                else if (exception is FileNotFoundException)
                {
                    // NOTE: This was only an example to demonstrate handling multiple exceptions.
                    //        It's more efficient to use File.Exists(fileName) rather than using an exception
                    //        to drive your logic.
                    Console.WriteLine("Error: File not found");
                }
                // Since we caught the generic System.Exception, this "else" case will
                // throw back up anything that wasn't explicitly caught:
                else
                {
                    throw;
                }
            }
            Console.ReadLine();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *