Not a member?     Existing members login below:

Fundamentals of Computer Programming with C#

Chapter 12. Exception
In This Chapter
In this chapter we will discuss exceptions in the object-oriented
programming and in C# in particular. We will learn how to handle
exceptions using the try-catch construct, how to pass them to the calling
methods and how to throw standard or our own exceptions using the
throw construct. We will give various examples for using exceptions. We will
look at the types of exceptions and the exceptions hierarchy in the .NET
Framework. At the end, we will look at the advantages of using exceptions,
best practices and how to apply them in different situations.
What Is an Exception?
When we write a program, we describe step-by-step what the computer must
do (at least in imperative programming; in the functional programming things
look a bit different) and in most of the cases we rely that the program will
execute normally. Indeed, most of the time, programs are following this
normal pattern, but there are some exceptions. Let’s say we want to read a
file and display its contents on the screen. Let’s assume the file is located on
a remote server and during the process of reading it, the connection goes
down. The file then will be only partially loaded. The program will not be able
to execute normally and show file’s contents on the screen. In this case, we
have an exception from the normal (and correct) program execution and this
exception must be reported to the user and/or the administrator.
Exception is a notification that something interrupts the normal
program execution. Exceptions provide a programming paradigm for
detecting and reacting to unexpected events. When an exception arises, the
state of the program is saved, the normal flow is interrupted and the control
is passed to an exception handler (if such exists in the current context).
Exceptions are raised or thrown by programming code that must send a
signal to the executing program about an error or an unusual situation.
For example, if we try to open a file, which doesn’t exist, the code responsible
for opening the file will detect this and will throw an exception with a proper
error message.