using System;
class Program
{
static void Main()
{
try
{
// Prompt user to enter two numbers
Console.Write("Enter the numerator: ");
int numerator = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the denominator: ");
int denominator = Convert.ToInt32(Console.ReadLine());
// Perform division
int result = Divide(numerator, denominator);
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
// Handle divide by zero exception
Console.WriteLine("Error: Cannot divide by zero.");
Console.WriteLine($"Exception Details: {ex.Message}");
}
catch (FormatException ex)
{
// Handle format exception (e.g., invalid input)
Console.WriteLine("Error: Invalid input. Please enter numeric values.");
Console.WriteLine($"Exception Details: {ex.Message}");
}
catch (Exception ex)
{
// Handle any other exceptions
Console.WriteLine("An unexpected error occurred.");
Console.WriteLine($"Exception Details: {ex.Message}");
}
finally
{
// Clean up resources (if any)
Console.WriteLine("Division operation completed.");
}
}
static int Divide(int x, int y)
{
return x / y;
}
}
Catch Specific Exceptions: Always catch specific exceptions before catching the general Exception to provide more precise error handling.
Avoid Empty Catch Blocks: Avoid using empty catch blocks, as they can mask important errors and make debugging difficult.
Use Finally for Cleanup: Use the finally block to release resources, such as file handles or database connections, ensuring that resource cleanup occurs even if an exception is thrown.