Try Catch문

정제로·2023년 8월 28일
0

C#

목록 보기
25/30

보통 예외처리를 할때, if else만 사용하거나 switch~case문을 자주 사용할거다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeamRPG;

namespace TeamRPG
{
    public class Utility
    {
        public static int CheckValidInput(int min, int max)
        {
            while (true)
            {
                string input = Console.ReadLine();
                try
                {
                    //------*** try catch----------
                    // 입력된 문자열을 정수로 변환 -> t, 정수 값 -> ret
                    // 실패 -> f , FormatException 발생.
                    bool parseSuccess = int.TryParse(input, out var ret);
                    if (!parseSuccess)
                    {
                        //throw new FormatException();
                        //throw new OverflowException();
                        throw new FormatException("알맞은 숫자를 다시 입력하세요.");
                    }
                    return ret;
                }
                catch (FormatException ex)
                {
                    // try에서 발생한 오류를 catch 블록에서 처리.
                    Console.WriteLine("알맞은 숫자가 아닙니다.\n" + ex.Message);
                    //-------------------------------------
                }
            }
        }
    }
}

이 코드를 보자.
기본적으로 try catch문은 try에서 예외를 catch로 던져줘야하는 식이다.
여러 Exception들을 만들어서 catch로 던져주고, catch에서는 해당 Exception을 받아서 catch문 안에 있는 코드를 출력해준다.

위의 코드는 입력받은 값이 숫자일때, 그 숫자로 무언가를 이용하려할때 사용하는 코드이다.
이 코드를 사용할때, if~else if~else문을 기본적으로 사용하지만, 거기에서 예외처리를 못해주는 경우까지 예외처리를 해주기 위해 사용했다.

profile
초보자입니다.. 잘못된 정보, 달게 받겠습니다..

0개의 댓글

관련 채용 정보