Answers for "how to handle inner exceptions"

C#
0

how to handle inner exceptions

using System;
using System.IO;

class HandleInnerExceptions
{
    static void Main()
    {
        try
        {
            ParseNumber("notANumber");
        }
        catch (Exception e) 
        {
            Console.WriteLine($"Inner Exception: {e.InnerException.Message}");
            Console.WriteLine($"Outer Exception: {e.Message}");
        }        
    }

    static void ParseNumber(string number)
    {
        try
        {
            // This will fail, and throw a FormatException
            var num = int.Parse(number);             
        }
        catch (FormatException fe)
        {
            try
            {
                // This file doesn't exist, and will throw a FileNotFoundException
                var log = File.Open("logs.txt", FileMode.Open);
            }
            catch
            {
                throw new FileNotFoundException("Could not open the log!", fe);
            }                              
        }
    }
}
Posted by: Guest on June-24-2021

Code answers related to "how to handle inner exceptions"

C# Answers by Framework

Browse Popular Code Answers by Language