예외는 프로그램의 한 부분에서 다른 부분으로 제어를 전송하는 방법을 제공합니다. C# 예외 처리는 try, catch, finally라는 네 가지 키워드를 기반으로 합니다. , 던지기 .
-
시도 - try 블록은 특정 예외가 활성화된 코드 블록을 식별합니다. 그 뒤에 하나 이상의 catch 블록이 옵니다.
-
잡다 − 프로그램은 문제를 처리하려는 프로그램의 위치에서 예외 처리기로 예외를 포착합니다. catch 키워드는 예외의 catch를 나타냅니다.
다음은 C#에서 try, catch 및 finally를 사용하는 방법을 보여주는 예입니다.
예
using System;
namespace Demo {
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();
}
}
} 출력
Result: 0