๊ด€๋ฆฌ ๋ฉ”๋‰ด

Algo ์“ฐ์ž

31. ์˜ˆ์™ธํ•„ํ„ฐ(Exception Filter) ๋ณธ๋ฌธ

๐Ÿ’ป Programming Language/C#

31. ์˜ˆ์™ธํ•„ํ„ฐ(Exception Filter)

S.Honey 2022. 4. 8. 09:10
  • Exception Filter : catch์ ˆ์ด ๋ฐ›์•„๋“ค์ผ ์˜ˆ์™ธ ๊ฐ์ฒด์— ์ œ์•ฝ์‚ฌํ•ญ์„ ์ฃผ๊ณ  ๊ทธ ์‚ฌํ•ญ์— ๋งŒ์กฑํ•˜๋Š” ๊ฒฝ์šฐ์—
    ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋ฅผ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋Š” ๊ธฐ๋Šฅ
    catch๋ฌธ ๋’ค์— when ํ‚ค์›Œ๋“œ๋ฅผ ์ด์šฉ.

์‚ฌ์šฉ์ž ์ •์˜ ์˜ˆ์™ธ ํด๋ž˜์Šค

  • ๋ชจ๋“  ์˜ˆ์™ธ ๊ฐ์ฒด๋Š” System.Exception ํด๋ž˜์Šค๋กœ๋ถ€ํ„ฐ ํŒŒ์ƒ๋œ๋‹ค.
  • ์‚ฌ์šฉ์ž ์ •์˜ ์˜ˆ์™ธ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค๋•Œ๋„ ์—ญ์‹œ System.Exception ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›์•„์„œ ๋งŒ๋“ ๋‹ค.

์‚ฌ์šฉ ์˜ˆ์ œ ์ฝ”๋“œ

using System.Collections;

namespace ExceptionEx
{
    // ์‚ฌ์šฉ์ž ์ •์˜ ์˜ˆ์™ธ ํด๋ž˜์Šค
    class UserException : Exception
    {
        public int ErrorCode { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try {
                Console.WriteLine("1 ~ 5์˜ ์ˆซ์ž ์ค‘ ํ•˜๋‚˜๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค : ");
                string numTxt = Console.ReadLine();

                int num = Int32.Parse(numTxt);

                if (num < 0 || num > 5)
                {
                    throw new UserException() { ErrorCode = num };
                }
                else
                {
                    Console.WriteLine($"{num}");
                }
            }
            catch (UserException e) when (e.ErrorCode < 0)
            {
                Console.WriteLine("์Œ์ˆ˜๋Š” ์ž…๋ ฅ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.");
            }
            catch (UserException e) when (e.ErrorCode > 5)
            {
                Console.WriteLine("5๋ณด๋‹ค ํฐ ์ˆ˜๋Š” ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.");
            }
        }
    }
}
Output

1 ~ 5์˜ ์ˆซ์ž ์ค‘ ํ•˜๋‚˜๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค :
-1
์Œ์ˆ˜๋Š” ์ž…๋ ฅ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

1 ~ 5์˜ ์ˆซ์ž ์ค‘ ํ•˜๋‚˜๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค :
6
5๋ณด๋‹ค ํฐ ์ˆ˜๋Š” ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.

1 ~ 5์˜ ์ˆซ์ž ์ค‘ ํ•˜๋‚˜๋ฅผ ์ž…๋ ฅํ•˜์‹œ์˜ค :
3
3