Chapter Eight: Exception Handling
Chapter Eight: Exception Handling
Exception Handling
1
Objectives
2
Objectives
3
Objectives
4
Understanding Exceptions
5
Understanding Exceptions
6
Common Language Runtime
• The Common Language Runtime (CLR),
the virtual machine component of
Microsoft's .NET framework, manages the
execution of .NET programs. A process
known as just-in-time compilation converts
compiled code into machine instructions
which the computer's CPU then executes
7
8
Purposely Generating a SystemException
9
Purposely Generating a SystemException
10
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
11
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
12
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
13
Understanding Object-Oriented Exception-
Handling Methods
16
Using the Exception Class’s ToString()
Method and Message Field
17
Catching Multiple Exceptions
18
Catching Multiple Exceptions
21
Catching Multiple Exceptions
22
Catching Multiple Exceptions
23
Catching Multiple Exceptions
25
Using the finally Block
26
Using the finally Block
27
Handling an Exception with a Loop
28
Throwing Exceptions
29
Throwing Exceptions
30
•Next Skip
31
Throwing Exceptions
33
Tracing Exceptions Through the Call Stack
34
Creating Your Own Exception Classes
35
Chapter Summary
36
Chapter Summary
37
Chapter Summary
38