아카이빙/C#

[C#] 예외처리

셩님 2018. 6. 21. 08:59

[C#] 예외처리

  • 프로그램을 짜다보면 예상치못한 경우가 발생할 수 있다.

  • 배열의 범위를 벗어나는 인덱스에 접근한다거나 어떤수를 0으로 나눈다거나...

  • 이런 예외가 발생하면 프로그램은 오류를 발생시키며 강제 종료된다.

  • 이를 막기 위해 필요한 부분에서는 예외처리를 해주어야 한다.

int[] a = {1, 2, 3};
for(int i=0; i<5; i++)
{
   Console.WriteLine(a[i]);
}
  • 프로그램이 종료된다.

try~catch

int[] a = {1, 2, 3};
for(int i=0; i<5; i++)
{
   try
  {
       Console.WriteLine(a[i]);
  }
   catch(IndexOutOfRangeException e)
  {
       Console.WriteLine(e.Message);
  }
}

1
2
3
Index was outside the bounds of the array.
Index was outside the bounds of the array.

System.Exception과 예외던지기

  • C#에서 모든 예외는 반드시 System.Exception 클래스를 상속받아야한다.

  • IndexOutOfRangeException, DivideByZeroException 등 여러 예외를 Exception 하나로 받을 수 있다.

    • 그러나 상황에 따라 섬세한 예외처리가 필요한 코드에서는 Exception 클래스만으로 예외 처리하는 것은 금물!

  • 또, 프로그래머가 예측한 예외 말고도 다른 예외 까지 받아낼 수 있다.

static void DoSomething(int arg)
{
   if (arg < 10)
       Console.WriteLine(arg);
   else
       throw new Exception("arg가 10보다 큽니다.");    
}

static void Main()
{
   try
  {
       DoSomething(1);
       DoSomething(3);
       DoSomething(6);
       DoSomething(13);
  }
   catch (Exception e)
  {
       Console.WriteLine(e.Message);
  }
}

try~catch와 finally

  • try 블록에서 코드를 실행하다가 예외를 던지면 프로그램이 catch절로 바로 뛰어 넘어온다.

  • 예외처리 때문에 try 블록에서 처리해야할 중요한 코드(파일 닫기나 자원 해제 등)가 실행되지 못하면 문제가 있다.

  • 이를 우아하게 처리하기 위해 finally 절을 제공한다.

static int Divide(int divisor, int divided)
{
   try
  {
       Console.WriteLine("Divide() Start");
       return divisor / divided;
  }
   catch (DivideByZeroException e)
  {
       Console.WriteLine("Divide() Exception occured");
       throw e;
  }
   finally
  {
       Console.WriteLine("Divide() End");
  }
}
  • 이 메소드를 실행하게 되면, 예외 여부에 상관없이 finally 절은 무조건 실행된다.

예외처리는,,,

  • 실제 일을하는 코드와 문제를 처리하는 코드를 분리할 수 있다.

  • 디버깅에도 용이하다.

  • 여러 문제점을 하나로 묶어내거나, 발생할 수 있는 오류를 종류별로 정리할 수 있다.


참조

  • 뇌를 자극하는 C# 5.0 프로그래밍, 박상현, 한빛미디어


'아카이빙 > C#' 카테고리의 다른 글

[C#] Delegate는 언제 사용하는가  (0) 2018.06.25
[C#] Delegate (대리자)  (0) 2018.06.25
[C#] 제네릭의 형식 제약  (0) 2018.06.21
[C#] 제네릭 클래스  (0) 2018.06.21
[C#] 제네릭 메소드  (0) 2018.06.21