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

마지막으로 C#의 키워드

<시간/>

finally 키워드는 예외가 발생했는지 여부에 관계없이 주어진 명령문 세트를 실행하는 블록으로 사용됩니다. 예를 들어 파일을 열면 예외 발생 여부에 관계없이 파일을 닫아야 합니다.

구문

다음은 구문입니다 -

try {
   // statements causing exception
} catch( ExceptionName e1 ) {
   // error handling code
} catch( ExceptionName e2 ) {
   // error handling code
} catch( ExceptionName eN ) {
   // error handling code
} finally {
   // statements to be executed
}

finally 블록을 구현하는 예를 살펴보겠습니다 -

using System;
public class Demo {
   int result;
   Demo() {
      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);
      }
   }
   public static void Main(string[] args) {
      Demo d = new Demo();
      d.division(100, 0);
   }
}

출력

이것은 다음과 같은 출력을 생성합니다 -

Exception caught = System.DivideByZeroException: Attempted to divide by zero.
   at Demo.division(Int32 num1, Int32 num2) in d:\Windows\Temp\n0kebv45.0.cs:line 11
Result = 0