Chapter Four
Exception Handling
1
Objectives
• Learn about exceptions and the Exception class
• How to purposely generate a SystemException
• Learn about traditional error-handling methods
• Learn about object-oriented exception-handling
methods
• How to use the Exception class’s ToString()
method and Message field
• How to catch multiple Exceptions
• How to use the finally block
2
Objectives
• How to handle an Exception with a loop
• How to throw an Exception
• How to trace Exceptions through the call stack
• How to create your own Exception classes
3
Understanding Exceptions
• An exception is any error condition or unexpected behavior in
an executing program
• Certain errors are called exceptions because they are not
usual occurrences
• The object-oriented technique used to manage exceptions
make up the group of methods known as exception handling
• In C#, all exceptions are objects
• C# .NET includes built-in exception classes for every possible
error. The Exception class is the base class of all the exception
classes.
• The following is a hierarchy of exception classes in .NET:
4
Understanding Exceptions
5
Understanding Exceptions
• Most exceptions you will use derive from two classes
that in turn derive from the Exception class
– The predefined Common Language Runtime exception
classes derived from SystemException
– The user-defined application exception classes you derive
from ApplicationException
6
Purposely Generating a SystemException
• The following figure shows how the NullReferenceException is
thrown in Visual Studio debug mode when you access a null
object property at runtime.
7
System Exception
Exception Class Description
ArgumentException Raised when a non-null argument that is passed to a method is invalid.
ArgumentNullException Raised when null argument is passed to a method.
ArgumentOutOfRangeException Raised when the value of an argument is outside the range of valid values.
DivideByZeroException Raised when an integer value is divide by zero.
FileNotFoundException Raised when a physical file does not exist at the specified location.
FormatException Raised when a value is not in an appropriate format to be converted from a string by a
conversion method such as Parse.
IndexOutOfRangeException Raised when an array index is outside the lower or upper bounds of an array or collection.
InvalidOperationException Raised when a method call is invalid in an object's current state.
KeyNotFoundException Raised when the specified key for accessing a member in a collection is not exists.
NotSupportedException Raised when a method or operation is not supported.
NullReferenceException Raised when program access members of null object.
OverflowException Raised when an arithmetic, casting, or conversion operation results in an overflow.
OutOfMemoryException Raised when a program does not get enough memory to execute the code.
StackOverflowException Raised when a stack in memory overflows.
TimeoutException The time interval allotted to an operation has expired. 8
Purposely Generating a SystemException
• The DivideByZeroException object below was generated
automatically by C#
• Just because an Exception occurs when an Exception object is
created, you don’t necessarily have to deal with it
9
Understanding Object-Oriented Exception-
Handling Methods
• In object-oriented terminology, you “try” a procedure that
may not complete correctly
• A method that detects an error condition or Exception
“throws” an Exception
• The block of code that processes the error “catches” the
Exception
10
Understanding Object-Oriented Exception-
Handling Methods
• When you write a block of code in which something
can go wrong, you can place the code in a try block,
consisting of:
– The keyword try
– An opening curly brace
– Statements that might cause Exceptions
– A closing curly brace
11
Understanding Object-Oriented Exception-
Handling Methods
• You create a catch block with the following elements:
– The keyword catch, followed by an opening parenthesis, the
Exception type, a name for an instance of the Exception type, and a
closing parenthesis
– An opening curly brace
– Statements that take the action you want to use to deal with the error
condition
– A closing curly brace
12
Understanding Object-Oriented Exception-
Handling Methods
• General form of a try…catch pair
13
Using the Exception Class’s ToString() Method
and Message Field
• Any Exception generated from within a try block would be
caught by a catch block whose argument is an Exception type
(e.g., Exception e); there is no way to confirm the origin of the
Exception
• You can use the ToString() method to provide a descriptive
error message
• The Exception class also contains a field named Message that
contains useful information about an Exception
14
Using the Exception Class’s ToString() Method
and Message Field
• Output of UsingTheException program when user enters 0 for second number
15
Catching Multiple Exceptions
• You can place as many statements as you need within a try
block, and you can catch as many different Exceptions as you
want
• If you place more than one statement in a try block, only the
first error-generating statement throws an Exception
• When multiple catch blocks are present, they are examined in
sequence until a match is found for the Exception that
occurred
16
17
Catching Multiple Exceptions
• TwoErrors class with two catch blocks
18
Catching Multiple Exceptions
• Output of TwoErrors program
19
Catching Multiple Exceptions
• If you reverse the two try statements within the TwoErrors
class, the output of the program changes
20
Catching Multiple Exceptions
• When you want to execute the same code, no matter what
type of Exception occurs, you can use only one catch block,
which receives type Exception
21
Catching Multiple Exceptions
• The Exception class is the base class for all Exception objects
and therefore can reference all Exception descendants
• The catch block in the previous code accepts all Exception
argument types
• When you list multiple catch blocks following a try, you must
be careful that some catch blocks don’t become unreachable
• Note: Multiple catch blocks with the same exception type are
not allowed. A catch block with the base Exception type must
be the last block.
22
Catching Multiple Exceptions
• Program with unreachable catch block
23
Catching Multiple Exceptions
• Error message generated by UnreachableCatch program
24
Using the finally Block
• The finally block is an optional block and should come after
a try or catch block.
• The code within a finally block executes whether or not the
try block identifies an Exception
• Typically, the finally block is used to perform clean-up tasks
• Note: Multiple finally blocks are not allowed.
• Also, the finally block cannot have the return, continue, or
break keywords.
• When you include a finally block, you are assured that the
finally statements will execute before the program is
abandoned
25
Using the finally Block
• General form of a try…catch block with a finally block 26
Handling an Exception with a Loop
• Different programs require different ways of handling
Exceptions
• In some cases, the try-catch sequence could be placed in a
loop that continues to execute until the code is successful
27
Nested try-catch
• C# allows nested try-catch blocks. When using nested try-catch blocks, an
exception will be caught in the first matching catch block that follows
the try block where an exception occurred.
28
Nested try-catch
• An inner catch block will be executed in the above
example because it is the first catch block that
handles all exception types.
• If there isn't an inner catch block that matches with
raised exception type, then the control will flow to
the outer catch block until it finds an appropriate
exception filter. Consider the following example.
29
Nested try-catch
30
Nested try-catch
• In the above example, an exception of
type DivideByZeroException will be raised.
• Because an inner catch block handles only
the NullReferenceTypeException, it will be
handle by an outer catch block.
31
Throwing Exceptions
• An advantage of using object-oriented exception-handling
techniques is the ability to deal with Exceptions appropriately
as you make conscious decisions about how to handle them
• When methods from other classes throw Exceptions, they
don’t have to catch them
• When you design your own classes that might cause
Exceptions, you should create them to throw the Exception
but not to handle it
• Handling an Exception should be left to the client (the
program that uses the class)
32
Throwing Exceptions
33
Creating Your Own Exception Classes
• You can create your own customized Exception class for your
application
• To create your own Exception that you can throw, you should
extend the ApplicationException class
• You should not create an excessive number of special
Exception types for your class because it adds a level of
complexity to your program
34
Creating Your Own Exception Classes
• For example, create InvalidStudentNameException class in a
school application, which does not allow any special character
or numeric value in a name of any of the students.
35
Creating Your Own Exception Classes
• Now, you can raise InvalidStudentNameException in your
program whenever the name contains special characters or
numbers.
• Use the throw keyword to raise an exception.
36
Creating Your Own Exception Classes
37
Chapter Summary
• An exception is any error condition or unexpected behavior in
an executing program
• You can purposely generate a SystemException exception by
forcing a program to contain an error
• When you think an error will occur frequently, it is most
efficient to handle it in the traditional way, with if statements
• In object-oriented terminology, you “try” a procedure that
may not complete correctly
38
Chapter Summary
• Every Exception object contains a ToString() method and a
Message field
• You can place as many statements as you need within a try
block, and you can catch as many different Exceptions as you
want
• When you have actions to perform at the end of a try…catch
sequence, you can use a finally block
• When you want to keep trying a block of code until some
value or state within a program is correct, you can place a
try…catch block within a loop
39
Chapter Summary
• When methods throw Exceptions, they don’t have to catch
them; instead, the program that calls a method that throws
an Exception can catch it and determine what to do
• When a method throws an Exception, if the method does not
catch it, then the Exception is thrown to the method that
called the offending method
• To create your own Exception that you can throw, you should
extend the ApplicationException class
40