예외처리

정영훈·2022년 12월 1일
0

C#프로그래밍

목록 보기
28/29

예외처리

디버거나 잡지 못하고 프로그램이 실행 중에 발생하는 오류를 예외(Exception)이라고 부른다. 또한 이런 예외를 대처할 수 있게 하는 것을 예외 처리(Exception Handling)이라고 한다.

실행 중 오류가 발생하는 상황은 다음과 같다.

  • 0으로 나눌 경우
  • 배열의 범위를 넘어 접근할 때
  • 메모리 오버플로우

다음과 같이 오류를 발생시켜 보면

class Test
{
    static void Main(string[] args)
    {
        int[] a = new int[10] { 1,2,3,4,5,6,7,8,9,10};
        Console.WriteLine(a[10]);
    }
}
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at Test.Main(String[] args) in C:\Users\jt26\OneDrive - gyo6.net\dev\C#\ConsoleApp27\ConsoleApp27\Program.cs:line 6

C:\Users\jt26\OneDrive - gyo6.net\dev\C#\ConsoleApp27\ConsoleApp27\bin\Debug\net6.0\ConsoleApp27.exe(프로세스 56004개)이(가) 종료되었습니다(코드: -532462766개).
이 창을 닫으려면 아무 키나 누르세요...

위와 같은 에러 메세지가 나타난다. 프로그래머가 예기치못한 예외의 상황이 발생하면 실행중인 프로그램이 비정상적으로 종류될 수 있다.

이렇게 예외가 발생하였을 때 처리하는 방법으로 try-catch문을 사용할 수 있다.

try-catch문

예외가 발생할 수 있는 부분을 try부분에 입력하고 예외가 발생할 경우 대처를 catch 부분에서 처리한다.

try
{
   //예외 발생
}
catch (Exception ex) 
{
   //여기처 처리
}
class Test
{
    static void Main(string[] args)
    {
        try
        {
            int[] a = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            Console.WriteLine(a[10]);
        }
        catch (Exception e)
        {
            Console.WriteLine("잘못된 범위에 접근했습니다.");
        }
    }
}

catch문은 여러개 작성도 가능하다. 여러개의 catch문 중 오류 상황을 찾아 if문 처럼 한개만 실행된다.

class Test
{
    static void Main(string[] args)
    {
        try
        {
            int[] a = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            Console.WriteLine(a[10]);
        }
        catch (IndexOutOfRangeException e) //배열의 범위를 벗어날 때
        {
            Console.WriteLine("잘못된 범위에 접근했습니다.");
        }
        catch (DivideByZeroException e) //0으로 나눌 때
        {
            Console.WriteLine("0으로 나눴습니다.");
        }
        catch(Exception e) //일반적인 오류 상태
        {
            Console.WriteLine("오류 발생");
        }
    }
}

finally는 오류가 발생하더라도 무조건 실행할 구문을 적어준다.

class Test
{
    static void Main(string[] args)
    {
        try
        {
            int[] a = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            Console.WriteLine(a[10]);
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("잘못된 범위에 접근했습니다.");
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine("0으로 나눴습니다.");
        }
        catch(Exception e)
        {
            Console.WriteLine("오류 발생");
        }
        finally
        {
            Console.WriteLine("오류 발생했습니다.");
        }
    }
}

다음과 같이 throw new Exception(); 구문을 통하여 강제로 오류를 발생시킬 수도 있다.

class Test
{
    static void Main(string[] args)
    {
        try
        {
            throw new Exception(); //강제 오류 발생
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("잘못된 범위에 접근했습니다.");
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine("0으로 나눴습니다.");
        }
        catch(Exception e) //강제 오류 발생 시 실행
        {
            Console.WriteLine("오류 발생");
        }
        finally
        {
            Console.WriteLine("오류 발생했습니다.");
        }
    }
}
profile
경북소프트웨어고등학교 정보교사

0개의 댓글