๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ–ฅ๏ธ/C#

[์ด๊ฒƒ์ด C#์ด๋‹ค] Chapter12: ์—ฐ์Šต๋ฌธ์ œ

by HanaV 2023. 8. 25.
728x90

1.์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ์ปดํŒŒ์ผํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์˜ˆ์™ธ๋ฅผ ํ‘œ์‹œํ•˜๊ณ  ๋น„์ •์ƒ์ ์œผ๋กœ ์ข…๋ฃŒํ•ฉ๋‹ˆ๋‹ค. try~catch๋ฌธ์„ ์ด์šฉํ•ด์„œ ์˜ˆ์™ธ๋ฅผ ์•ˆ์ „ํ•˜๊ฒŒ ์žก์•„ ์ฒ˜๋ฆฌํ•˜๋„๋ก ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•˜์„ธ์š”.

using System;

namespace Ex12_1
{
    class MainApp
    {
        static void Main()
        {
            int[] arr = new int[10];
            
            for(int i = 0; i < 10; ++i)
                arr[i] = i;
                
            for(int i = 0; i < 11; ++i)
                Console.WriteLine(arr[i]);
        }
    }
}
0
1
2
3
4
5
6
7
8
9
์ฒ˜๋ฆฌ๋˜์ง€ ์•Š์€ ์˜ˆ์™ธ: System.IndexOutOfRangeException: ์ธ๋ฑ์Šค๊ฐ€ ๋ฐฐ์—ด ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚ฌ์Šต๋‹ˆ๋‹ค.

try catch๋กœ ๋ฌถ์–ด์ฃผ๋ฉด ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‹ค.

using System;
using System.Collections.Generic;
using System.Text;

namespace Chapter12.Practice
{
    class MainApp
    {
        static void Main()
        {
            try
            {
                int[] arr = new int[10];

                for (int i = 0; i < 10; ++i)
                {
                    arr[i] = i;
                }

                for (int i = 0; i < 11; ++i)
                {
                    Console.WriteLine(arr[i]);
                }
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine("์˜ˆ์™ธ ๋ฐœ์ƒ: " + e.GetType()+ ": " + e.Message);
            }
        }
    }
}
728x90

"); wcs_do();