VioletaBabel

5일차 본문

기본개념/C#
5일차
Beabletoet 2018. 1. 22. 14:02

예외 처리

섬세한 처리를 요구하는게 아니라 예외를 싸그리 다룰 경우엔 IndexOutOfRangeException이 아닌 그냥 Exception을 쓴다.

1
2
3
4
5
6
7
8
9
10
            int[] ar = { 012 };
            try
            {//실행할 코드
                for (int i = 0; i < 5++i)
                    Console.WriteLine(ar[i]);
            }
            catch(IndexOutOfRangeException e)
            {//인덱스 범위 초과 시
                Console.WriteLine("Error! IndexOutOfRangeException!");
            }
cs



예외 던지기 - throw문

throw로 예외를 던지고 try~catch로 받는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
        static void UnderTen(int a)
        {
            if (a < 10)
                Console.WriteLine(a);
            else // a가 9보다 클 경우에는 에러를 던진다.
                throw new Exception("error : a > 9");
        }
        static void Main(string[] args)
        {
            try
            {
                UnderTen(8);
                UnderTen(9);
                UnderTen(10);
            }
            catch (Exception e)
            { //에러 출력
                Console.WriteLine(e.Message);
            }
        }
cs



finally

try~catch문 뒤에 사용. 예외 처리를 할 때에도 마무리로 해야할 코드는 finally에 넣는다.

자원을 해제한다거나, Open한 걸 Close한다거나 할 때 사용.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
            try
            {
                string t = Console.ReadLine();
                int d1 = Convert.ToInt32(t);
                t = Console.ReadLine();
                int d2 = Convert.ToInt32(t);
                Console.WriteLine("{0}/{1}={2}", d1, d2, d1 / d2);
            }
            catch(FormatException e)
            {//입력이 잘못된 형식
                Console.WriteLine(e.Message);
            }
            catch(DivideByZeroException e)
            {//0으로 나눔
                Console.WriteLine(e.Message);
            }
            finally
            {
                Console.WriteLine("Program Quit");
            }
cs


'기본개념 > C#' 카테고리의 다른 글

68. 코드 리뷰 입문  (0) 2018.11.20
6일차  (0) 2018.01.23
4일차  (0) 2018.01.21
3일차  (0) 2018.01.19
2일차  (0) 2018.01.18
Comments