본문 바로가기
NOTE/Programming

[C#] 예외처리

by DevAthena 2018. 4. 1.

출저 참고 : http://blog.eairship.kr/149 (누구나가 다 이해할 수 있는 프로그래밍 첫걸음 블로그)

를 공부하면서 나중에 다시보기 쉽게 정리한 것입니다. 원본은 위 글입니다.!


try~catch 문

1
2
3
4
5
6
7
8
try
{
    // ...
}
catch (Exception e)
{
    // 예외 발생 시 처리부분
}
cs



- 예외가 발생할만한 코드를 try 문에 넣고 catch문은 예외 발생시 처리할 코드를 넣는다.

- 사용 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication35
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Division(50));
            Console.WriteLine(Division(102));
            Console.WriteLine(Division(497));
        }
 
        static int Division(int a, int b)
        {
            try
            {
                return a / b;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine(e.Message);
                return -1;
            }
        }
    }
}
cs


결과 : 0으로 나누려 했습니다.

 -1

 5

 7




finally 문

1
2
3
4
5
6
7
8
9
10
11
12
try
{
   // ...
}
catch (Exception e)
{
   // ...
}
finally
{
   // 반드시 실행되는 코드
}
cs



- try 문에서 예외가 발생하더라도 마지막에 무조건 실행되는 영역

- 자원을 해제하거나, 열려 있는 파일 등을 닫을 때 사용


- 사용 예시

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
 
namespace ConsoleApplication35
{
    class ClassFinally
    {
        public static void Main()
        {
            StreamReader sreader = null;
            StreamWriter swriter = null;
 
            try
            {
                sreader = new StreamReader(File.Open("A.txt", FileMode.Open));
                swriter = new StreamWriter(File.Open("B.txt", FileMode.Append, FileAccess.Write));
 
                while (sreader.Peek() != -1)
                {
                    swriter.WriteLine(sreader.ReadLine());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                if (sreader != null) sreader.Close();
                if (swriter != null) swriter.Close();
            }
        }
    }
}
cs



throw 문

- 예외를 던지는 역할

- 상위 호출 메소드로 Exception 객체를 전달하는 데 쓰임.

- try~catch 내에서 사용 될 수도 있고, 독립적으로도 사용 가능.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication35
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine(Division(102));
                Console.WriteLine(Division(497));
                Console.WriteLine(Division(5-1));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
 
        static int Division(int a, int b)
        {
            if (a <= 0 || b <= 0)
                throw new Exception("0 또는 음수가 오는 것을 허용하지 않습니다.");
            else
                return a / b;
        }
    }
}
cs


결과 : 5

 7

 0 또는 음수가 오는 것을 허용하지 않습니다.




 


'NOTE > Programming' 카테고리의 다른 글

[C#] Reflection && Attributes  (0) 2018.04.01
[C#] 컬렉션  (0) 2018.04.01
[C#] 인터페이스  (0) 2018.04.01
[C#] 확장 메소드, 분할 클래스, 중첩 클래스  (0) 2018.04.01
[C#] 클래스의 상속  (0) 2018.04.01