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

2020. 1. 26. 18:41C# 언어/이것이 C# 이다. 연습문제

반응형

 

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

 

0
1
2
3
4
5
6
7
8
9

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

예외 처리 전

using System;
using static System.Console;

namespace ch12
{
    class Program
    {
        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++)
                WriteLine(arr[i]);
        }
    }
}

 

예외 처리 후

using System;
using static System.Console;

namespace ch12
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[10];
            for (int i = 0; i < 10; i++)
            {
                arr[i] = i;
            }

            try
            {
                for (int i = 0; i < 11; i++)
                {
                    WriteLine(arr[i]);
                }
            }
            catch (IndexOutOfRangeException e)
            {
                Array.Resize(ref arr, arr.Length + 1);
                WriteLine("출력중 배열의 크기를 벗어났습니다.\n배열의 크기를 조정했습니다.");
            }
        }
    }
}

 

저는 배열의 크기를 늘리는 것으로 예외를 처리했습니다.

방법은 여러가지 입니다.

 

반복문의 반복수를 줄여도 되고

단순히 출력만 해주어도 예외 처리가 됩니다.

반응형