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

Algo ์“ฐ์ž

29. System.Exceptionํด๋ž˜์Šค, throw๋ฌธ ๋ณธ๋ฌธ

๐Ÿ’ป Programming Language/C#

29. System.Exceptionํด๋ž˜์Šค, throw๋ฌธ

S.Honey 2022. 4. 7. 09:41
  • System.Exception ํด๋ž˜์Šค๋Š” ๋ชจ๋“  Exception์˜ Baseํด๋ž˜์Šค์ด๋‹ค.
    • ๋ชจ๋“  Exception๋“ค์€ System.Exception ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›๋Š”๋‹ค.
    • ์•ž์„œ ์‚ฌ์šฉํ–ˆ๋˜ IndexOutOfRangeException ์˜ˆ์™ธ ํด๋ž˜์Šค๋„ System.Exception์œผ๋กœ๋ถ€ํ„ฐ ํŒŒ์ƒ๋œ ๊ฒƒ

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

throw๋ฌธ ํ˜•์‹

    try
    {
       throw new Exception("์˜ˆ์™ธ๋ฅผ ๋˜์ง");
    }
    catch(Exception e)
    {
        Console.WriteLine(e.Message);
    }

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

using System.Collections;

namespace ExceptionEx
{

    class Program
    {
        static void throwMethod(int aa)
        {
            if (aa < 5 ) { Console.WriteLine($"{aa}"); }
            else { throw new Exception("aa๋Š” 5๋ณด๋‹ค ํฌ๋‹ค."); }
        }
        static void Main(string[] args)
        {
            try 
            { 
            throwMethod(1);
            throwMethod(2);
            throwMethod(3);
            throwMethod(4);
            throwMethod(5); // => catch ๋ฌธ์œผ๋กœ ๋„˜์–ด๊ฐ„
            throwMethod(6); // 6์€ ์ˆ˜ํ–‰๋˜์ง€ ์•Š์Œ. 
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("์ข…๋ฃŒ");
        }
    }
}
Output

1
2
3
4
aa๋Š” 5๋ณด๋‹ค ํฌ๋‹ค.
์ข…๋ฃŒ

  • try๋ฌธ ๋‚ด์—์„œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด try๋ฌธ ๋‚ด ์ฝ”๋“œ๋ฅผ ๋ชจ๋‘ ์‹คํ–‰ํ•˜์ง€ ์•Š๊ณ  catch๋ฌธ์œผ๋กœ ์˜ˆ์™ธ๋ฅผ ๋˜์ง€๋ฉฐ ๋„˜์–ด๊ฐ„๋‹ค.
  • ์ดํ›„ catch๋ฌธ ๋‚ด ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•œ ๋’ค catch๋ฌธ์„ ๋ฒ—์–ด๋‚˜ ๋‹ค๋ฅธ ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•˜๊ณ  ํ”„๋กœ๊ทธ๋žจ์„ ์ •์ƒ ์ข…๋ฃŒํ•œ๋‹ค.
  • ์ฆ‰, try๋ฌธ ๋‚ด์—์„œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ํ•ด๋‹น try๋ฌธ ๋‚ด์—์„œ์˜ ๋™์ž‘์€ ์ค‘์ง€ํ•˜์ง€๋งŒ ํ”„๋กœ๊ทธ๋žจ์˜ ์ „์ฒด์ ์ธ ๋™์ž‘์€ ์ •์ƒ์ ์œผ๋กœ ๋™์ž‘ํ•œ๋‹ค.