Skip to Main Content
C# 2008 Programmer's Reference
book

C# 2008 Programmer's Reference

by Wei-Meng Lee
November 2008
Intermediate to advanced content levelIntermediate to advanced
838 pages
16h 26m
English
Wrox
Content preview from C# 2008 Programmer's Reference

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 or num2.

  • If the user enters a non-numeric value for num1 and num2 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# 5.0 Programmer's Reference

C# 5.0 Programmer's Reference

Rod Stephens
Learning C# 2005, 2nd Edition

Learning C# 2005, 2nd Edition

Jesse Liberty, Brian MacDonald
A Programmer's Guide to C# 5.0, 4th Edition

A Programmer's Guide to C# 5.0, 4th Edition

Eric Gunnerson, Nick Wienholt
Beginning C# 6.0 Programming with Visual Studio 2015

Beginning C# 6.0 Programming with Visual Studio 2015

Benjamin Perkins, Jacob Vibe Hammer, Jon D. Reid

Publisher Resources

ISBN: 9780470285817Purchase book