Вы находитесь на странице: 1из 17

1

Topic 11 Exception Handling

Outline
11.1
11.2
11.3
11.4
11.5
11.6
11.7
11.8

Introduction
Exception Handling Overview
Example: DivideByZeroException
.NET Exception Hierarchy
finally Block
Exception Properties
Programmer-Defined Exception Classes
Handling Overflows with Operators checked and unchecked

2002 Prentice Hall. All rights reserved.

11.1 Introduction
Exception handling
Create application that can handle or resolve exception

Enable clear, robust and more fault-tolerant programs

2002 Prentice Hall. All rights reserved.

11.2 Exception Handling Overview


Keywords
Try
Include codes in which exceptions might occur

Catch
Represent types of exceptions the catch can handle

Finally
(Optional) codes present here will always execute

Exception handling

Process synchronous errors


Follows the termination model of exception handling

2002 Prentice Hall. All rights reserved.

11.2 Exception Handling Overview


Catch type
Must be of class Exception or one that extends it directly or
indirectly

Stack unwinding

CLR attempt to locate an enclosing try block in a calling


method

2002 Prentice Hall. All rights reserved.

11.3 Example: DivideByZeroException


Error catching
Method Convert.ToInt32 will automatically detect for
invalid representation of an integer
Method generates a FormatException

CLR automatic detection for division by zero

Occurrence will cause a DivideByZeroException

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

Outline

// Fig 11.1: DivideByZeroTest.cs


// Basics of C# exception handling.
using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;

DivideByZeroTest
.cs

// class demonstrates how to handle exceptions from


// division by zero in integer arithmetic and from
// improper numeric formatting
public class DivideByZeroTest : System.Windows.Forms.Form
{
private System.Windows.Forms.Label numeratorLabel;
private System.Windows.Forms.TextBox numeratorTextBox;
private System.Windows.Forms.Label denominatorLabel;
private System.Windows.Forms.TextBox denominatorTextBox;
private System.Windows.Forms.Button divideButton;
private System.Windows.Forms.Label outputLabel;
// required designer variable
private System.ComponentModel.Container components = null;
// default constructor
public DivideByZeroTest()
{
// required for Windows Form Designer support
InitializeComponent();
}

2002 Prentice Hall.


All rights reserved.

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

Outline

// main entry point for the application


[STAThread]
static void Main()
{
Application.Run( new DivideByZeroTest() );
}

DivideByZeroTest
.cs

// Visual Studio .NET generated code


// obtain integers input by user and divide numerator
// by denominator
private void divideButton_Click(
object sender, System.EventArgs e )
{
outputLabel.Text = "";

Try block encloses codes that could


call result
Quotient
in a throw exception

// retrieve user input and


try
{
// Convert.ToInt32 generates FormatException if
// argument is not an integer
int numerator = Convert.ToInt32( numeratorTextBox.Text );
int denominator =
Convert.ToInt32( denominatorTextBox.Text );
// division
generates
DivideByZeroException
FormatException
thrown
if it
// denominator is 0
cannot convert
string=into
integer / denominator;
int result
numerator

if

DivideByZeroException
thrown if denominator is zero

outputLabel.Text = result.ToString();
} // end try

Will not be reached (executed) if


an exception is thrown

2002 Prentice Hall.


All rights reserved.

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

// process invalid number format


catch ( FormatException )
Catch handler for
{
FormatException
MessageBox.Show( "You must enter two integers",
"Invalid Number Format",
Keyword
MessageBoxButtons.OK, MessageBoxIcon.Error );
}

Message box to display

// user attempted to divide by zero


error message divideByZeroException )
catch ( DivideByZeroException
{
MessageBox.Show( divideByZeroException.Message,
"Attempted to Divide by Zero",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
} // end method divideButton_Click

Outline

DivideByZeroTest
.cs
Catch handler for
DivideByZeroException

Handler uses property


Message of class Exception

} // end class DivideByZeroTest

2002 Prentice Hall.


All rights reserved.

Outline

DivideByZeroTest
.cs
Program Output
When incorrect format
are entered into either
input fields

When attempting to
diving by zero

2002 Prentice Hall.


All rights reserved.

10

11.4 .NET Exception Hierarchy


.Net Framework
Class Exception is base class
Derived class:

ApplicationException
Programmer use to create data types specific to their
application
Low chance of program stopping execution
SystemException
CLR can generate at any point during execution
Runtime exceptin
Example: IndexOutOfRangeException

2002 Prentice Hall. All rights reserved.

11

11.5 Finally Block


Resource leak
Improper allocation of memory

Finally block

Ideal for placing resource deallocation code


Execute immediately after catch handler or try block
Must be present if no catch block is present
Is optional if more than one or more catch handler exist

2002 Prentice Hall. All rights reserved.

12

11.5 Finally Block


The Throw expression

An exception object
Must be of either class Exception or one of its derived class
Customize the exception type thrown from methods

2002 Prentice Hall. All rights reserved.

13

11.7 Programmer-Defined Exception Classes


Creating customized exception types
Should derive from class ApplicationException
Should end with Exception
Should define three constructors

A default constructor
A constructor that receives a string argument
A constructor that takes a string argument and an Exception
argument

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

Outline

// Fig 11:4: NegativeNumberException.cs


// NegativeNumberException represents exceptions caused by illegal
// operations performed on negative numbers
using System;

NegativeNumberEx
ception.cs

// NegativeNumberException represents exceptions caused by


// illegal operations performed on negative numbers
class NegativeNumberException : ApplicationException
Class NegativeNumberException
{
derives
from
ApplicationException
This represent the
default
constructor
// default constructor
public NegativeNumberException()
: base( "Illegal operation for a negative number" )
{
}
// constructor for customizing error message
public NegativeNumberException( string message )
: base( message )
{
}
// constructor for customizing error message and
// specifying inner exception object
public NegativeNumberException(
string message, Exception inner )
: base( message, inner )
{
}

14

This is a constructor that takes


in a string argument

This is a constructor that takes


in a string argument and an
Exception argument

} // end class NegativeNumberException

2002 Prentice Hall.


All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

Outline

// Fig 11.5: SquareRootTest.cs


// Demonstrating a programmer-defined exception class.
using
using
using
using
using
using

System;
System.Drawing;
System.Collections;
System.ComponentModel;
System.Windows.Forms;
System.Data;

15

SquareRootTest.c
s

// accepts input and computes the square root of that input


public class SquareRootTest : System.Windows.Forms.Form
{
private System.Windows.Forms.Label inputLabel;
private System.Windows.Forms.TextBox inputTextBox;
private System.Windows.Forms.Button squareRootButton;
private System.Windows.Forms.Label outputLabel;
// Required designer variable.
private System.ComponentModel.Container components = null;
// default constructor
public SquareRootTest()
{
// Required for Windows Form Designer support
InitializeComponent();
}
// Visual Studio .NET generated code

2002 Prentice Hall.


All rights reserved.

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

// main entry point for the application


[STAThread]
static void Main()
{
Application.Run( new SquareRootTest() );
}
// computes the square root of its parameter; throws
// NegativeNumberException if parameter is negative
public double SquareRoot( double operand )
{
// if negative operand, throw NegativeNumberException
if ( operand < 0 )
throw new NegativeNumberException(
"Square root of negative number not permitted" );

Outline

16

SquareRootTest.c
s

SqaureRoot throws a
NegativeNumberException

// compute the square root


return Math.Sqrt( operand );
} // end class SquareRoot
// obtain user input, convert to double and calculate
// square root
private void squareRootButton_Click(
object sender, System.EventArgs e )
{
outputLabel.Text = "";

A FormatException occurs if
NegativeNumberExceptions thrown
not a valid number from user
Try block invoke SqaureRoot

// catch any
try
{
double result =
SquareRoot( Double.Parse( inputTextBox.Text ) );

2002 Prentice Hall.


All rights reserved.

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87

Outline

outputLabel.Text = result.ToString();
}

17

Process the exception caused


SquareRootTest.c
s

// process invalid number format


by FormatException
catch ( FormatException notInteger )
{
MessageBox.Show( notInteger.Message,
"Invalid Operation", MessageBoxButtons.OK,
MessageBoxIcon.Error );
}

Catch handler takes care of the


NegativeNumberException

// display MessageBox if negative number input


catch ( NegativeNumberException error )
{
MessageBox.Show( error.Message, "Invalid Operation",
MessageBoxButtons.OK, MessageBoxIcon.Error );
Output showing
}

correct function

} // end method squareRootButton_Click


} // end class SquareRootTest

When attempting
to take a negative
square root

2002 Prentice Hall.


All rights reserved.

Вам также может понравиться