Book Review/이것이 C# 이다

이것이 C#이다 연습문제 12장

메론러버 2021. 3. 14. 14:44

1. 아래의 코드를 컴파일하면 다음과 같이 예외를 표시하고 비정상적으로 종료합니다.  try~catch문을 이용해서 예외를 안전하게 잡아 처리하도록 코드를 수정하세요.

 

0
1
2
3
4
5
6
7
8
9

처리되지 않은 예외: System.IndexOfRangeException: 인덱스가 배열 범위를 벗어났습니다.
위치: Ex12_1.MainApp.Main(String[] args) 파일 C:\Users\Sean\AppData\Local\TempraryProject\Ex12_1\MainApp.cs cs:줄 9

 

예외 처리 전

using System;

namespace Ex12_1
{
    class MainApp
    {
        Exception exception = null;

        static void Main(string[] args)
        {
            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]);
        }
    }
}

 

예외 처리 후

using System;

namespace Ex12_1
{
    class MainApp
    {
        Exception exception = null;

        static void Main(string[] args)
        {
            int[] arr = new int[10];
            int index = 0;
            try
            {
                for (int i = 0; i < 10; i++)
                    arr[i] = i;

                for (int i = 0; i < 11; i++)
                {
                    index = i;
                    Console.WriteLine(arr[i]);
                }
                
            }
            catch (IndexOutOfRangeException e) when (index > arr.Length)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.Message);
            }
        }
    }
}

 

예외 처리 후 Console 화면

 

 

 

============================================================================

 

[ References ]

 

jaeho0613.tistory.com/78?category=823121