• 회원가입
  • 로그인
  • 구글아이디로 로그인

[class] C# - Exceptions (= Try...Catch..) - 에러 제어

5,722  
목차
  1. Exceptions 정의
  2. try...catch... 구문
  3. finally 구문
  4. throw 키워드

 

Exceptions 정의

 

에러는 (의도적, 잘못 입력, 예측 불가 등) 여러 요인으로 생기는데,

C#은 프로그램 실행 중 에러 발생 시, 멈춘 후 에러 메세지를 생성.

즉, 정상적 실행의 예외적 경우 (= 오류)를 다루는 기술을 의미함.

 

 

try...catch... 구문

[구문]

 

try 

{

  //  테스트 할 실행 코드

}

catch(Exception e) 

{

  //  에러 발생 시 실행할 코드

}

 

PS. try...catch... 구문은 쌍으로 함께 사용.


[에러 발생 시, try...catch... 구문으로 처리 안 한 경우]

: C#의 기본 에러메세지가 그대로 노출됨. 

 

[예제] Program.cs

 

using System;

namespace Homzzang

{

  class Program

  {

    static void Main(string[] args)

    {

      int[] nums = {1, 2, 3};

      Console.WriteLine(nums[5]); // 에러 발생.

    }

  }

}

 

결과값:

Unhandled Exception:  

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' ....

[에러 발생 시, try...catch... 기본 구문으로 처리한 경우] 

 

파일명: Program.cs

 

using System;

namespace Homzzang

{

  class Program

  {

    static void Main(string[] args)

    {

      try

      {

        int[] nums = {1, 2, 3};

        Console.WriteLine(nums[5]);

      }

      catch (Exception e)

      {

        Console.WriteLine(e.Message);

      }

    }

  }

}

 

결과값: Index was outside the bounds of the array.


[에러 발생 시, try...catch... 사용자 정의 구문으로 처리한 경우]

※ e.Message 대신, "뭔가 오류 발생." 사용자 정의 문구를 출력.

 

파일명: Program.cs

 

using System;

namespace Homzzang

{

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                int[] nums = {1, 2, 3};

                Console.WriteLine(nums[5]);

            }

            catch (Exception e)

            {

                Console.WriteLine("뭔가 오류 발생.");

            }

        }

    }

}

 

결과값: 뭔가 오류 발생.

 

finally 구문

 

try...catch...구문 결과와 무관하게 그 이후에 실행할 코드 정의.

 


[예제] Program.cs

 

using System;

namespace Homzzang

{

  class Program

  {

    static void Main(string[] args)

    {

      try

      {

        int[] nums = {1, 2, 3};

        Console.WriteLine(nums[10]);

      }

      catch (Exception e)

      {

        Console.WriteLine("뭔가 오류 발생.");

      }  

      finally

      {

        Console.WriteLine("'try catch' 구문 종료.");

      }  

    }

  }

}

 

결과값:

뭔가 오류 발생.

'try catch' 구문 종료. 

 

throw 키워드

 

사용자 지정 오류 생성.

 


 

1. 

exception 클래스와 함께 사용

 

2.

C#엔 다양한 exception 클래스 있음. (예)

ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException, 기타 등등.

 


[에러 발생 O]

 

using System;

namespace Homzzang

{

  class Program

  {

    static void checkLevel(int level)

    {

      if (level < 3)

      {

        throw new ArithmeticException("이용 불가.");

      }

      else

      {

        Console.WriteLine("이용 가능.");

      }

    }


    static void Main(string[] args)

    {

      checkLevel(2);

    }

  }

}

 

결과값:

Unhandled Exception: 

System.ArithmeticException: 이용 불가. ...


[에러 발생 X]

 

using System;

namespace Homzzang

{

  class Program

  {

    static void checkLevel(int level)

    {

      if (level < 3)

      {

        throw new ArithmeticException("이용 불가.");

      }

      else

      {

        Console.WriteLine("이용 가능.");

      }

    }


    static void Main(string[] args)

    {

      checkLevel(3);

    }

  }

}


결과값: 이용 가능.



분류 제목
basic C# - Home (입문) - 추천 링크
basic C# - Intro (소개) - 용도・특징
basic C# - Start (시작) - Visual Studio Community 설치/실행/세팅
basic C# - Syntax (구문)
basic C# - Output (출력)
basic C# - New Lines (줄바꿈)
basic C# - Comment (주석)
basic C# - Variable (변수)
basic C# - User Input (사용자 입력)
basic C# - Data Type (데이터 타입) - 자료형 (종류 + 변환)
basic C# - Operator (연산자)
basic C# - String (문자열)
basic C# - Math (수학)
basic C# - Boolean (참거짓)
basic C# - If ... Else - (이프 조건문)
basic C# - Switch (스위치 조건문)
basic C# - While Loop (와일 반복문)
basic C# - For Loop (포 반복문)
basic C# - Break/Continue (브레이크/컨티뉴) 키워드 - 반복문 빠져나가기 / 특정 조건 건너띄기
basic C# - Arrays (배열)
1/2
목록
찾아주셔서 감사합니다. Since 2012