c# ☃️

[C#] 예외처리 - try/catch/finally

소로리 산적 2024. 3. 25. 06:02
namespace TryCatchEx;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter a number");
        string userInput = Console.ReadLine();

        int userInputAsInput = int.Parse(userInput);


    }
}

이상한 입력값이 들어오면 막힘

예외처리 방법

namespace TryCatchEx;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter a number");
        string userInput = Console.ReadLine();

        try
        {
            int userInputAsInput = int.Parse(userInput);
        }
        catch (Exception)
        {
            Console.WriteLine("Format exception. please enter the correct type next time");
        }
       
    }
}

try 문안에 오류 발생시 catch 문을 탐

결과



상세한 오류 발생 사유를 만들 수 도 있음

namespace TryCatchEx;
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter a number");
        string userInput = Console.ReadLine();

        try
        {
            int userInputAsInput = int.Parse(userInput);
        }
        catch (FormatException)
        {
            Console.WriteLine("Format exception. please enter the correct type next time");


        }
        catch (OverflowException)
        {
            Console.WriteLine("Overflow Exception");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("Argument Exception, the value was empty(null)");
        }
        finally
        {
            //무조건 탐 
            Console.WriteLine("This is called always");
        }
       
    }
}