How to capture divide by zero exception in C#?
Answers
Answer:
System.DivideByZeroException is a class that handles errors generated from dividing a dividend with zero.
Let us see an example −
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();
}
}
}
The values entered here is num1/ num2 −
result = num1 / num2;
Above, if num2 is set to 0, then the DivideByZeroException is caught since we have handled exception above.
Explanation: