Exercise
Exceptions
Objetive
Write a C# program to prompt the user for two numbers and display their division. Errors should be caught using "try..catch"
Example Code
using System; // Import the System namespace, which contains fundamental classes like Console
class Program // Define the Program class
{
static void Main() // The entry point of the program
{
try // Start the try block to catch potential errors
{
// Ask the user for the first number (numerator)
Console.Write("Enter the first number (numerator): ");
int num1 = int.Parse(Console.ReadLine()); // Read and convert the first input to an integer
// Ask the user for the second number (denominator)
Console.Write("Enter the second number (denominator): ");
int num2 = int.Parse(Console.ReadLine()); // Read and convert the second input to an integer
// Perform the division and display the result
int result = num1 / num2; // Divide the first number by the second
Console.WriteLine($"The result of {num1} divided by {num2} is: {result}"); // Output the result
}
catch (DivideByZeroException) // Catch the specific exception when trying to divide by zero
{
// Handle the divide by zero error
Console.WriteLine("Error: Cannot divide by zero."); // Display an error message
}
catch (FormatException) // Catch the format exception if the user doesn't input valid integers
{
// Handle the invalid input error
Console.WriteLine("Error: Please enter valid integers."); // Display an error message
}
catch (Exception ex) // Catch any other unexpected exceptions
{
// Handle any general exception
Console.WriteLine($"An unexpected error occurred: {ex.Message}"); // Display a general error message
}
}
}