Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 try catch의 흐름 제어 finally

<시간/>

try, catch, finally의 흐름 제어는 다음 예를 사용하여 이해할 수 있습니다. 여기서 우리는 두 개의 숫자를 나눕니다 -

예시

using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;
      DivNumbers() {
         result = 0;
      }
      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}

출력

Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in :0
Result: 0

다음은 C#에서 try catch finally를 사용한 예외 처리의 흐름 제어를 보여줍니다.

  • try 블록에서 예외가 발생하면 제어가 catch 블록으로 넘어갑니다.
  • catch 블록이 완료된 후 finally 블록이 작동합니다.
  • 예외가 발생하지 않으면 먼저 시도가 발생한 다음 마지막으로 차단하는 흐름 제어