Programming Course in C# ¡Free!

Exceptions

 Friday, April 05, 2013 published by Exercises C#
Proposed exercise

Create a program to ask the user for two numbers and display their division. Errors must be trapped using "try..catch".


Output



Solution


using System;
public class Exceptions
{
public static void Main()
{        
Console.Write("Enter a number to divide: ");
int number1 = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter another number to divide: ");
int number2 = Convert.ToInt32(Console.ReadLine());

int division;
try
{
division = number1 / number2;

Console.WriteLine("{0} / {1} = {2}", number1, number2, division);
}

catch ( DivideByZeroException )
{
Console.WriteLine("Cannot divide by 0");
return;
}
}
}