Chapter 12. Exception Handling
An exception is a situation that occurs when your program encounters an error that it is not expecting during runtime. Examples of exceptions include trying to divide a number by zero, trying to write to a file that is read-only, trying to delete a nonexistent file, and trying to access more members of an array than it actually holds. Exceptions are part and parcel of an application, and as a programmer you need to look out for them by handling the various exceptions that may occur. That means your program must be capable of responding to the exceptions by offering some ways to remedy the problem instead of exiting midway through your program (that is, crashing).
Handling Exceptions
To understand the importance of handling exceptions, consider the following case, a classic example of dividing two numbers:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApp { class Program { static void Main(string[] args) { int num1, num2, result; Console.Write("Please enter the first number:"); num1 = int.Parse(Console.ReadLine()); Console.Write("Please enter the second number:"); num2 = int.Parse(Console.ReadLine()); result = num1 / num2;
Console.WriteLine("The result of {0}/{1} is {2}", num1, num2, result); Console.ReadLine(); } } }
In this example, there are several opportunities for exceptions to occur:
If the user enters a noninteger value for
num1
ornum2
.If the user enters a non-numeric value for
num1
andnum2 ...
Get C# 2008 Programmer's Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.