๐Ÿ’ป Programming Language/C#

28. ์˜ˆ์™ธ์ฒ˜๋ฆฌ(Exception Handling)

S.Honey 2022. 4. 7. 09:39

์˜ˆ์™ธ ์ฒ˜๋ฆฌ ๊ตฌ๋ฌธ(try - catch)

try{
    // ์‹คํ–‰์ฝ”๋“œ
}
catch(Exception ๊ฐ์ฒด1){
    // ์–ด๋–ค ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„๋•Œ ์ฒ˜๋ฆฌ ์ฝ”๋“œ
}
catch(Exception ๊ฐ์ฒด2){
    // catch๋ฌธ์€ ์—ฌ๋Ÿฌ๊ฐœ๊ฐ€ ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.
}
...

Ex - ๊ธฐ์กด ์˜ˆ์™ธ ๋ฐœ์ƒ ์ฝ”๋“œ

namespace ExceptionEx
{   
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = {1,2,3,4,5};
            for(int i = 0; i < 6; i++)
            {
                Console.WriteLine(array[i]);
            }
            Console.WriteLine("ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ!!");
        }
    }
}
Output

1
2
3
4
5
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at ExceptionEx.Program.Main(String[] args) in C:\Users\shkim\source\repos\ClassEx\practice1\Program.cs:line 31 
  • ์˜ˆ์™ธ ๋ฐœ์ƒ์‹œ ์‹คํ–‰ํ•˜๋˜ ํ”„๋กœ๊ทธ๋žจ์ด ์˜ˆ์™ธ๋ฅผ ์ถœ๋ ฅํ•˜๋ฉฐ ์ค‘์ง€๋˜๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

  • ์ด๋•Œ try - catch ๊ตฌ๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ์˜ˆ์™ธ๋ฅผ ์ฒ˜๋ฆฌํ•ด์ฃผ๋ฉด ํ”„๋กœ๊ทธ๋žจ์ด ์ค‘์ง€ํ•˜์ง€ ์•Š๋Š”๋‹ค.


Ex - Use try-catch

using System.Collections;
namespace ExceptionEx
{   
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int[] array = { 1, 2, 3, 4, 5 };
                for (int i = 0; i < 6; i++)
                {
                    Console.WriteLine(array[i]);
                }
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine($"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. : {e.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. : {e.Message}");
            }

            Console.WriteLine("ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ!!");
        }
    }
}
Output

1
2
3
4
5
์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. : Index was outside the bounds of the array.
ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ!!
  • ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ๋ฉ”์„ธ์ง€๊ฐ€ ๋‚˜์˜ด. => ์˜ค๋ฅ˜๋Š” ์žก๊ณ  ํ”„๋กœ๊ทธ๋žจ์ด ์ค‘์ง€๊ฐ€ ๋˜๋Š” ํ˜„์ƒ์ด ๋ฐœ์ƒํ•˜์ง€ ์•Š์Œ. ๋งˆ์ง€๋ง‰๊นŒ์ง€ ์ •์ƒ์ ์œผ๋กœ ์ˆ˜ํ–‰๋จ.