Locked lesson.
About this lesson
By anticipating specific kinds of Exceptions, you can program your code to treat them in unique ways without crashing.
Exercise files
Download this lesson’s related exercise files.
40 - Catching Specific Exceptions.docx61 KB 40 - Catching Specific Exceptions SOLUTION.docx
59.3 KB
Quick reference
Catching Specific Exceptions
If you know what exception your code will throw, you can take specific action.
When to use
Do this when you know what exception your code will throw.
Instructions
try
{
Console.WriteLine("Enter A Number");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Another Number");
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(x / y);
}
catch (FormatException)
{
Console.WriteLine("Hey! Enter a Number not a Letter!");
}
catch (DivideByZeroException)
{
Console.WriteLine("Hey! You can't divide by zero!");
}
Hints & tips
- You can take specific action based on the exception that occurs.
Lesson notes are only available for subscribers.