2002 prentice hall. all rights reserved. 1 chapter 11 – exception handling outline...

34
2002 Prentice Hall. All rights reserved. 1 Chapter 11 – Exception Handling Outline 11.1 Introduction 11.2 Exception Handling Overview 11.3 Example: DivideByZeroException 11.4 .NET Exception Hierarchy 11.5 Finally Block 11.6 Exception Properties 11.7 Programmer-Defined Exception Classes 11.8 Handling Overflows

Post on 22-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

2002 Prentice Hall. All rights reserved.

1

Chapter 11 – Exception Handling

Outline11.1 Introduction11.2   Exception Handling Overview11.3   Example: DivideByZeroException11.4   .NET Exception Hierarchy11.5   Finally Block11.6   Exception Properties11.7   Programmer-Defined Exception Classes11.8   Handling Overflows

2002 Prentice Hall. All rights reserved.

2

11.1 Introduction

• Exception– Indication of problem during program’s execution

– Although problem can occur, it occurs infrequently

2002 Prentice Hall. All rights reserved.

3

11.1 Introduction

• Exception handling– Clear, robust and more fault-tolerant programs

• Continue normal execution

– Sever problems• Prevent normal execution

– Notification

– Termination

2002 Prentice Hall. All rights reserved.

4

11.2   Exception Handling Overview

• Program detects error– Throws exception (throw point)

• Caught by exception handler

– Handled

• Uncaught (no appropriate exception handler)

– Debug mode

• Ignore, continue execution

• View in debugger

– Standard execution mode

• Ignore, continue execution

• Terminate

2002 Prentice Hall. All rights reserved.

5

11.2   Exception Handling Overview

• Try block– Encloses code in which errors may occur

2002 Prentice Hall. All rights reserved.

6

11.2   Exception Handling Overview

• Catch block (Catch handler)– Appears after Try block

• Parameter included

– Handles specific exception type

• Parameterless

– Handles all exception types

2002 Prentice Hall. All rights reserved.

7

11.2   Exception Handling Overview

• Finally block– Appears after last Catch handler

– Optional (if one or more catch handlers exist)

– Encloses code that always executes

2002 Prentice Hall.All rights reserved.

Outline8

DivideByZeroTest.vb

1 ' Fig. 11.1: DivideByZeroTest.vb2 ' Basics of Visual Basic exception handling.3 4 Imports System.Windows.Forms.Form5 6 Public Class FrmDivideByZero7 Inherits Form8 9 ' label and TextBox for specifying numerator10 Friend WithEvents lblNumerator As Label11 Friend WithEvents txtNumerator As TextBox12 13 ' label and TextBox for specifying denominator14 Friend WithEvents lblDenominator As Label15 Friend WithEvents txtDenominator As TextBox16 17 ' button for dividing numerator by denominator18 Friend WithEvents cmdDivide As Button19 20 Friend WithEvents lblOutput As Label ' output for division21 22 ' Windows Form Designer generated code23 24 ' obtain integers from user and divide numerator by denominator25 Private Sub cmdDivide_Click(ByVal sender As System.Object, _26 ByVal e As System.EventArgs) Handles cmdDivide.Click27 28 lblOutput.Text = ""29 30 ' retrieve user input and call Quotient31 Try32 Keyword Try indicates beginning of Try block

Try block encloses code in which errors may occur

2002 Prentice Hall.All rights reserved.

Outline9

DivideByZeroTest.vb

33 ' Convert.ToInt32 generates FormatException if argument34 ' is not an integer35 Dim numerator As Integer = _36 Convert.ToInt32(txtNumerator.Text)37 38 Dim denominator As Integer = _39 Convert.ToInt32(txtDenominator.Text)40 41 ' division generates DivideByZeroException if 42 ' denominator is 043 Dim result As Integer = numerator \ denominator44 45 lblOutput.Text = result.ToString()46 47 ' process invalid number format48 Catch formattingException As FormatException49 MessageBox.Show("You must enter two integers", _50 "Invalid Number Format", MessageBoxButtons.OK, _51 MessageBoxIcon.Error)52 53 ' user attempted to divide by zero54 Catch dividingException As DivideByZeroException55 MessageBox.Show(dividingException.Message, _56 "Attempted to Divide by Zero", _57 MessageBoxButtons.OK, MessageBoxIcon.Error)58 59 End Try60 61 End Sub ' cmdDivide_Click62 63 End Class ' FrmDivideByZero

If either exception occursthe Try block expires

The appropriate errormessage dialog is

displayed for the user

Type of exception that theCatch block can handle

If the denominator is zero the CLR throws a

DivideByZeroException

2002 Prentice Hall.All rights reserved.

Outline10

DivideByZeroTest.vb

2002 Prentice Hall. All rights reserved.

11

11.4   .NET Exception Hierarchy

• Class Exception – Base class of .NET Framework exception hierarchy

• Important classes derived from Exception– ApplicationException

• Can create exception data types specific to applications

– SystemException• Runtime exceptions

– Can occur anytime during execution

– Avoid with proper coding

2002 Prentice Hall. All rights reserved.

12

11.4   .NET Exception Hierarchy

• Benefit of hierarchy– Inheritance

• If handling behavior same for base and derived classes

– Able to catch base class

– Otherwise catch derived classes individually

• Ex.– Catch handler with parameter type Exception

• Able to catch all exceptions

2002 Prentice Hall. All rights reserved.

13

11.5   Finally Block

• Encloses code that always executes– Code executes whether exception occurs or not

• Optional – Not required if one or more catch handlers exist

• Why use Finally block?– Typically releases resources acquired in Try block

• Helps eliminate resource leaks

2002 Prentice Hall.All rights reserved.

Outline14

UsingExceptions.vb

1 ' Fig 11.2: UsingExceptions.vb2 ' Using Finally blocks.3 4 ' demonstrating that Finally always executes5 Class CUsingExceptions6 7 ' entry point for application8 Shared Sub Main()9 10 ' Case 1: No exceptions occur in called method11 Console.WriteLine("Calling DoesNotThrowException")12 DoesNotThrowException()13 14 ' Case 2: Exception occurs and is caught in called method15 Console.WriteLine(vbCrLf & _16 "Calling ThrowExceptionWithCatch")17 18 ThrowExceptionWithCatch()19 20 ' Case 3: Exception occurs, but not caught in called method 21 ' because no Catch block.22 Console.WriteLine(vbCrLf & _23 "Calling ThrowExceptionWithoutCatch")24 25 ' call ThrowExceptionWithoutCatch26 Try27 ThrowExceptionWithoutCatch()28 29 ' process exception returned from ThrowExceptionWithoutCatch30 Catch31 Console.WriteLine("Caught exception from " & _32 "ThrowExceptionWithoutCatch in Main")33 34 End Try35

Main invokes methodDoesNotThrowException

Main invokes methodThrowExceptionWithCatch

Main invokes methodThrowExceptionWithoutCatch

Try block enables Main tocatch any exceptions thrown by ThrowExceptionWithoutCatch

2002 Prentice Hall.All rights reserved.

Outline15

UsingExceptions.vb

36 ' Case 4: Exception occurs and is caught in called method,37 ' then rethrown to caller.38 Console.WriteLine(vbCrLf & _39 "Calling ThrowExceptionCatchRethrow")40 41 ' call ThrowExceptionCatchRethrow42 Try43 ThrowExceptionCatchRethrow()44 45 ' process exception returned from ThrowExceptionCatchRethrow46 Catch47 Console.WriteLine("Caught exception from " & _48 "ThrowExceptionCatchRethrow in Main")49 50 End Try51 52 End Sub ' Main53 54 ' no exceptions thrown55 Public Shared Sub DoesNotThrowException()56 57 ' Try block does not throw any exceptions 58 Try59 Console.WriteLine("In DoesNotThrowException")60 61 ' this Catch never executes62 Catch63 Console.WriteLine("This Catch never executes")64 65 ' Finally executes because corresponding Try executed66 Finally67 Console.WriteLine( _68 "Finally executed in DoesNotThrowException")69 70 End Try

Program control ignores Catch handler because the Try block does not throw

an exception

Finally block executesdisplaying a message

Methods are Shared so Maincan invoke them directly

Try block enables Main tocatch any exceptions thrown by ThrowExceptionCatchRethrow

Main invokes methodThrowExceptionCatchRethrow

2002 Prentice Hall.All rights reserved.

Outline16

UsingExceptions.vb

71 72 Console.WriteLine("End of DoesNotThrowException")73 End Sub ' DoesNotThrowException74 75 ' throws exception and catches it locally76 Public Shared Sub ThrowExceptionWithCatch()77 78 ' Try block throws exception79 Try80 Console.WriteLine("In ThrowExceptionWithCatch")81 82 Throw New Exception( _83 "Exception in ThrowExceptionWithCatch")84 85 ' catch exception thrown in Try block86 Catch exception As Exception87 Console.WriteLine("Message: " & exception.Message)88 89 ' Finally executes because corresponding Try executed90 Finally91 Console.WriteLine( _92 "Finally executed in ThrowExceptionWithCatch")93 94 End Try95 96 Console.WriteLine("End of ThrowExceptionWithCatch")97 End Sub ' ThrowExceptionWithCatch98 99 ' throws exception and does not catch it locally100 Public Shared Sub ThrowExceptionWithoutCatch()101 102 ' throw exception, but do not catch it103 Try104 Console.WriteLine("In ThrowExceptionWithoutCatch")105

DoesNotThrowException endsand program control returns to Main

Try block creates an exceptionobject and uses Throw statement

to throw the object

This string becomes the exception object’s error message

and the Try block expires

ThrowExceptionWithCatch endsand program control returns to Main

Finally block executesdisplaying a message

The specified exception typematches the type thrown so

the exception is caughtand a message is displayed

Program control continues at first Catch handler following the Try

2002 Prentice Hall.All rights reserved.

Outline17

UsingExceptions.vb

106 Throw New Exception( _107 "Exception in ThrowExceptionWithoutCatch")108 109 ' Finally executes because corresponding Try executed110 Finally111 Console.WriteLine("Finally executed in " & _112 "ThrowExceptionWithoutCatch")113 114 End Try115 116 ' unreachable code; would generate syntax error 117 118 End Sub ' ThrowExceptionWithoutCatch119 120 ' throws exception, catches it and rethrows it121 Public Shared Sub ThrowExceptionCatchRethrow()122 123 ' Try block throws exception124 Try125 Console.WriteLine("Method ThrowExceptionCatchRethrow")126 127 Throw New Exception( _128 "Exception in ThrowExceptionCatchRethrow")129 130 ' catch any exception, place in object error131 Catch exception As Exception132 Console.WriteLine("Message: " & exception.Message)133 134 ' rethrow exception for further processing135 Throw exception136 137 ' unreachable code; would generate syntax error138

Exception is not caught because there are no catch handlers

Finally block executesdisplaying a message

Program control returns to Mainwhere the exception is caught

Exception is caughtand rethrown

2002 Prentice Hall.All rights reserved.

Outline18

UsingExceptions.vb

139 ' Finally executes because corresponding Try executed140 Finally141 Console.WriteLine("Finally executed in ThrowException")142 143 End Try144 145 ' any code placed here is never reached146 147 End Sub ' ThrowExceptionCatchRethrow148 149 End Class ' UsingExceptions

Calling DoesNotThrowExceptionIn DoesNotThrowExceptionFinally executed in DoesNotThrowExceptionEnd of DoesNotThrowException Calling ThrowExceptionWithCatchIn ThrowExceptionWithCatchMessage: Exception in ThrowExceptionWithCatchFinally executed in ThrowExceptionWithCatchEnd of ThrowExceptionWithCatch Calling ThrowExceptionWithoutCatchIn ThrowExceptionWithoutCatchFinally executed in ThrowExceptionWithoutCatchCaught exception from ThrowExceptionWithoutCatch in Main Calling ThrowExceptionCatchRethrowMethod ThrowExceptionCatchRethrowMessage: Exception in ThrowExceptionCatchRethrowFinally executed in ThrowExceptionCaught exception from ThrowExceptionCatchRethrow in Main

Program control returns to Mainwhere the exception is caught

Finally block executesdisplaying a message

2002 Prentice Hall. All rights reserved.

19

11.6   Exception Properties

• Property Message– Stores exception object’s error message

• Default message

– Associated with exception type

• Customized message

– Passed to exception object’s constructor

2002 Prentice Hall. All rights reserved.

20

11.6   Exception Properties

• Property StackTrace– Contains method-call stack in a String

• Sequential list of methods that had not finished processing at time of exception

• Stack-unwinding – Attempting to locate appropriate Catch handler for uncaught

exception

2002 Prentice Hall. All rights reserved.

21

11.6   Exception Properties

• Property InnerException– Allows programmers to “wrap” exception objects with other

exception objects

– Original exception object becomes InnerException of new exception object

– Benefit• Allows programmers to provide more information about

particular exceptions

2002 Prentice Hall. All rights reserved.

22

11.6   Exception Properties

• Others– Property Helplink

• Location of help file(description of problem)

– Property Source• Name of application where exception occurred

– Property TargetSite• Method where exception originated

2002 Prentice Hall.All rights reserved.

Outline23

Properties.vb

1 ' Fig. 11.3: Properties.vb2 ' Stack unwinding and Exception class properties.3 4 ' demonstrates using properties Message, StackTrace and 5 ' InnerException6 Class CProperties7 8 Shared Sub Main()9 10 ' call Method1; any Exception generatesd will be caught11 ' in the Catch block that follows12 Try13 Method1()14 15 ' Output String representation of Exception, then output16 ' values of properties InnerException, Message and StackTrace17 Catch exception As Exception18 Console.WriteLine("exception.ToString: " & _19 vbCrLf & "{0}" & vbCrLf, exception.ToString())20 21 Console.WriteLine("exception.Message: " & _22 vbCrLf & "{0}" & vbCrLf, exception.Message)23 24 Console.WriteLine("exception.StackTrace: " & _25 vbCrLf & "{0}" & vbCrLf, exception.StackTrace)26 27 Console.WriteLine("exception.InnerException: " & _28 vbCrLf & "{0}" & vbCrLf, exception.InnerException)29 30 End Try31 32 End Sub ' Main33

Invocation of Main, whichbecomes the first method on the method-call stack

Main invokes Method 1, whichbecomes the second method

on the method-call stack

Exception is caught bycatch handler

2002 Prentice Hall.All rights reserved.

Outline24

Properties.vb

34 ' calls Method235 Public Shared Sub Method1()36 Method2()37 End Sub38 39 ' calls Method340 Public Shared Sub Method2()41 Method3()42 End Sub43 44 ' throws an Exception containing InnerException45 Public Shared Sub Method3()46 47 ' attempt to convert String to Integer48 Try49 Convert.ToInt32("Not an integer")50 51 ' wrap FormatException in new Exception52 Catch formatException As FormatException53 54 Throw New Exception("Exception occurred in Method3", _55 formatException)56 57 End Try58 59 End Sub ' Method360 61 End Class ' CProperties

exception.ToString:System.Exception: Exception occurred in Method3 ---> System.FormatException: Input String was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)

Method 1 invokes Method 2, which becomes the third

method on the stack

Method 2 invokes Method 3,which becomes the fourth

method on the stack

Method 3 invokes methodConvert.ToInt32

Because the argument is not in Integer format an exception is thrown

and Convert.ToInt32 is removedfrom the stack

The specified exception typematches the type thrown so

the exception is caught

The FormatException ispassed to the constructor

as an InnerException

Method 3 terminatesand unwinding begins

2002 Prentice Hall.All rights reserved.

Outline25

Properties.vb

at System.Int32.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int32.Parse(String s) at System.Convert.ToInt32(String value) at Properties.CProperties.Method3() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 49 --- End of inner exception stack trace --- at Properties.CProperties.Method3() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 54 at Properties.CProperties.Method2() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 41 at Properties.CProperties.Method1() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 36 at Properties.CProperties.Main() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 13 exception.Message:Exception occurred in Method3 exception.StackTrace: at Properties.CProperties.Method3() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 54 at Properties.CProperties.Method2() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 41 at Properties.CProperties.Method1() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 36 at Properties.CProperties.Main() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 13

2002 Prentice Hall.All rights reserved.

Outline26

Properties.vb

exception.InnerException:System.FormatException: Input String was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int32.Parse(String s) at System.Convert.ToInt32(String value) at Properties.CProperties.Method3() in C:\books\2001\vbhtp2\ch11\Fig11_03\Properties\Properties.vb:line 49

2002 Prentice Hall. All rights reserved.

27

11.7   Programmer-Defined Exception Classes

• Programmer-defined exceptions should:– Derive directly/indirectly from class ApplicationException

– Have class name ending in “Exception”

– Define three constructors• Default constructor

• Constructor that receives String argument

– The error message

• Constructor that receives String argument and an Exception argument

– The error message

– The InnerException object

2002 Prentice Hall.All rights reserved.

Outline28

NegativeNumberException.vb

1 ' Fig. 11.4: NegativeNumberException.vb2 ' NegativeNumberException represents exceptions caused by3 ' illegal operations performed on negative numbers.4 5 Public Class NegativeNumberException6 Inherits ApplicationException7 8 ' default constructor9 Public Sub New()10 MyBase.New("Illegal operation for a negative number")11 End Sub12 13 ' constructor for customizing error message14 Public Sub New(ByVal messageValue As String)15 MyBase.New(messageValue)16 End Sub17 18 ' constructor for customizing error message and specifying19 ' inner exception object20 Public Sub New(ByVal messageValue As String, _21 ByVal inner As Exception)22 23 MyBase.New(messageValue, inner)24 End Sub25 26 End Class ' NegativeNumberException

2002 Prentice Hall.All rights reserved.

Outline29

SquareRootTest.vb

1 ' Fig. 11.5: SquareRootTest.vb2 ' Demonstrating a user-defined exception class.3 4 Imports System.Windows.Forms5 6 Public Class FrmSquareRoot7 Inherits Form8 9 ' Label for showing square root10 Friend WithEvents lblOutput As Label11 Friend WithEvents lblInput As Label12 13 ' Button invokes square-root calculation14 Friend WithEvents cmdSquareRoot As Button15 16 ' TextBox receives user's Integer input17 Friend WithEvents txtInput As TextBox18 19 ' Windows Form Designer generated code20 21 ' computes square root of parameter; throws 22 ' NegativeNumberException if parameter is negative23 Public Function SquareRoot(ByVal operand As Double) As Double24 25 ' if negative operand, throw NegativeNumberException26 If operand < 0 Then27 Throw New NegativeNumberException( _28 "Square root of negative number not permitted")29 30 End If31 32 ' compute square root33 Return Math.Sqrt(operand)34 35 End Function ' cmdSquareRoot

If numeric value entered is negative a NegativeNumberException

is thrown

Method Sqrt of class Math

2002 Prentice Hall.All rights reserved.

Outline30

SquareRootTest.vb

36 37 ' obtain user input, convert to double and calculate square root38 Private Sub cmdSquareRoot_Click( _39 ByVal sender As System.Object, _40 ByVal e As System.EventArgs) Handles cmdSquareRoot.Click41 42 lblOutput.Text = ""43 44 ' catch any NegativeNumberException thrown45 Try46 Dim result As Double = _47 SquareRoot(Convert.ToDouble(txtInput.Text))48 49 lblOutput.Text = result.ToString()50 51 ' process invalid number format52 Catch formatException As FormatException53 MessageBox.Show(formatException.Message, _54 "Invalid Number Format", MessageBoxButtons.OK, _55 MessageBoxIcon.Error)56 57 ' diplay MessageBox if negative number input58 Catch negativeNumberException As NegativeNumberException59 MessageBox.Show(negativeNumberException.Message, _60 "Invalid Operation", MessageBoxButtons.OK, _61 MessageBoxIcon.Error)62 63 End Try64 65 End Sub ' cmdSquareRoot_Click66 67 End Class ' FrmSquareRoot

2002 Prentice Hall.All rights reserved.

Outline31

SquareRootTest.vb

2002 Prentice Hall. All rights reserved.

32

11.8   Handling Overflows

• Visual Basic enables user to specify whether arithmetic occurs in:– Checked context

• Default

• CLR throws OverflowException if overflow occurs

– Unchecked context• Overflow produces truncated result

2002 Prentice Hall.All rights reserved.

Outline33

Overflow.vb

1 ' Fig. 11.6: Overflow.vb2 ' Demonstrating overflows with and without checking.3 4 ' demonstrates overflows with and without checking5 Class COverflow6 7 Shared Sub Main()8 9 ' calculate sum of number1 and number 210 Try11 12 Dim number1 As Integer = Int32.MaxValue ' 2,147,483,64713 Dim number2 As Integer = Int32.MaxValue ' 2,147,483,64714 Dim sum As Integer = 015 16 ' output numbers17 Console.WriteLine("number1: {0}" & vbCrLf & _18 "number2: {1}", number1, number2)19 20 Console.WriteLine(vbCrLf & _21 "Sum integers in checked context:")22 23 sum = number1 + number2 ' compute sum24 25 ' this statement will not throw OverflowException if user26 ' removes integer-overflow checks27 Console.WriteLine(vbCrLf & _28 "Sum after operation: {0}", sum)29 30 ' catch overflow exception31 Catch exceptionInformation As OverflowException32 Console.WriteLine(exceptionInformation.ToString())33 34 End Try35

2002 Prentice Hall.All rights reserved.

Outline34

Overflow.vb

36 End Sub ' Main37 38 End Class ' COverflow

number1: 2147483647number2: 2147483647 Sum integers in checked context:System.OverflowException: Arithmetic operation resulted in an overflow. at Overflow.COverflow.Main() in C:\books\2001\vbhtp2\ch11\Overflow\Overflow.vb:line 23

number1: 2147483647number2: 2147483647 Sum integers in checked context: Sum after operation: -2