html5-img
1 / 34

Chapter 11 – Exception Handling

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.

dereklopez
Télécharger la présentation

Chapter 11 – Exception Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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

  2. 11.1 Introduction • Exception • Indication of problem during program’s execution • Although problem can occur, it occurs infrequently

  3. 11.1 Introduction • Exception handling • Clear, robust and more fault-tolerant programs • Continue normal execution • Sever problems • Prevent normal execution • Notification • Termination

  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

  5. 11.2   Exception Handling Overview • Try block • Encloses code in which errors may occur

  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

  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

  8. Keyword Try indicates beginning of Try blockTry block encloses code in which errors may occur 1 ' Fig. 11.1: DivideByZeroTest.vb 2 ' Basics of Visual Basic exception handling. 3 4 Imports System.Windows.Forms.Form 5 6 Public Class FrmDivideByZero 7 Inherits Form 8 9 ' label and TextBox for specifying numerator 10 Friend WithEvents lblNumerator As Label 11 Friend WithEvents txtNumerator As TextBox 12 13 ' label and TextBox for specifying denominator 14 Friend WithEvents lblDenominator As Label 15 Friend WithEvents txtDenominator As TextBox 16 17 ' button for dividing numerator by denominator 18 Friend WithEvents cmdDivide As Button 19 20 Friend WithEvents lblOutput As Label ' output for division 21 22 ' Windows Form Designer generated code 23 24 ' obtain integers from user and divide numerator by denominator 25 Private Sub cmdDivide_Click(ByVal sender As System.Object, _ 26 ByVal e As System.EventArgs) Handles cmdDivide.Click 27 28 lblOutput.Text = "" 29 30 ' retrieve user input and call Quotient 31Try 32 DivideByZeroTest.vb

  9. Type of exception that theCatch block can handle If either exception occursthe Try block expires If the denominator is zero the CLR throws a DivideByZeroException The appropriate errormessage dialog is displayed for the user 33 ' Convert.ToInt32 generates FormatException if argument 34 ' is not an integer 35 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 0 43 Dim result As Integer = numerator \ denominator 44 45 lblOutput.Text = result.ToString() 46 47 ' process invalid number format 48Catch formattingException As FormatException 49 MessageBox.Show("You must enter two integers", _ 50 "Invalid Number Format", MessageBoxButtons.OK, _ 51 MessageBoxIcon.Error) 52 53 ' user attempted to divide by zero 54 Catch dividingException As DivideByZeroException 55 MessageBox.Show(dividingException.Message, _ 56"Attempted to Divide by Zero", _ 57 MessageBoxButtons.OK, MessageBoxIcon.Error) 58 59 End Try 60 61 End Sub' cmdDivide_Click 62 63 End Class' FrmDivideByZero DivideByZeroTest.vb

  10. DivideByZeroTest.vb

  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

  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

  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

  14. Main invokes methodDoesNotThrowException Main invokes methodThrowExceptionWithCatch Main invokes methodThrowExceptionWithoutCatch Try block enables Main tocatch any exceptions thrown by ThrowExceptionWithoutCatch 1 ' Fig 11.2: UsingExceptions.vb 2 ' Using Finally blocks. 3 4 ' demonstrating that Finally always executes 5 Class CUsingExceptions 6 7 ' entry point for application 8 Shared Sub Main() 9 10 ' Case 1: No exceptions occur in called method 11 Console.WriteLine("Calling DoesNotThrowException") 12 DoesNotThrowException() 13 14 ' Case 2: Exception occurs and is caught in called method 15 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 ThrowExceptionWithoutCatch 26 Try 27 ThrowExceptionWithoutCatch() 28 29 ' process exception returned from ThrowExceptionWithoutCatch 30Catch 31 Console.WriteLine("Caught exception from " & _ 32 "ThrowExceptionWithoutCatch in Main") 33 34 End Try 35 UsingExceptions.vb

  15. Try block enables Main tocatch any exceptions thrown by ThrowExceptionCatchRethrow Main invokes methodThrowExceptionCatchRethrow Methods are Shared so Maincan invoke them directly Program control ignores Catch handler because the Try block does not throw an exception Finally block executesdisplaying a message 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 ThrowExceptionCatchRethrow 42 Try 43 ThrowExceptionCatchRethrow() 44 45 ' process exception returned from ThrowExceptionCatchRethrow 46 Catch 47 Console.WriteLine("Caught exception from " & _ 48 "ThrowExceptionCatchRethrow in Main") 49 50 End Try 51 52 End Sub' Main 53 54 ' no exceptions thrown 55Public Shared Sub DoesNotThrowException() 56 57 ' Try block does not throw any exceptions 58 Try 59 Console.WriteLine("In DoesNotThrowException") 60 61 ' this Catch never executes 62 Catch 63 Console.WriteLine("This Catch never executes") 64 65 ' Finally executes because corresponding Try executed 66 Finally 67 Console.WriteLine( _ 68 "Finally executed in DoesNotThrowException") 69 70 End Try UsingExceptions.vb

  16. 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 messageand the Try block expires Program control continues at first Catch handler following the Try The specified exception typematches the type thrown sothe exception is caughtand a message is displayed Finally block executesdisplaying a message ThrowExceptionWithCatch endsand program control returns to Main 71 72 Console.WriteLine("End of DoesNotThrowException") 73End Sub' DoesNotThrowException 74 75 ' throws exception and catches it locally 76 Public Shared Sub ThrowExceptionWithCatch() 77 78 ' Try block throws exception 79 Try 80 Console.WriteLine("In ThrowExceptionWithCatch") 81 82Throw New Exception( _ 83"Exception in ThrowExceptionWithCatch") 84 85 ' catch exception thrown in Try block 86Catch exception As Exception 87 Console.WriteLine("Message: " & exception.Message) 88 89 ' Finally executes because corresponding Try executed 90 Finally 91 Console.WriteLine( _ 92 "Finally executed in ThrowExceptionWithCatch") 93 94 End Try 95 96 Console.WriteLine("End of ThrowExceptionWithCatch") 97End Sub' ThrowExceptionWithCatch 98 99 ' throws exception and does not catch it locally 100 Public Shared Sub ThrowExceptionWithoutCatch() 101 102 ' throw exception, but do not catch it 103 Try 104 Console.WriteLine("In ThrowExceptionWithoutCatch") 105 UsingExceptions.vb

  17. 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 106Throw New Exception( _ 107 "Exception in ThrowExceptionWithoutCatch") 108 109 ' Finally executes because corresponding Try executed 110 Finally 111 Console.WriteLine("Finally executed in " & _ 112 "ThrowExceptionWithoutCatch") 113 114 End Try 115 116 ' unreachable code; would generate syntax error 117 118End Sub ' ThrowExceptionWithoutCatch 119 120 ' throws exception, catches it and rethrows it 121 Public Shared Sub ThrowExceptionCatchRethrow() 122 123 ' Try block throws exception 124 Try 125 Console.WriteLine("Method ThrowExceptionCatchRethrow") 126 127 Throw New Exception( _ 128 "Exception in ThrowExceptionCatchRethrow") 129 130 ' catch any exception, place in object error 131 Catch exception As Exception 132 Console.WriteLine("Message: " & exception.Message) 133 134 ' rethrow exception for further processing 135 Throw exception 136 137 ' unreachable code; would generate syntax error 138 UsingExceptions.vb

  18. Finally block executesdisplaying a message Program control returns to Mainwhere the exception is caught 139 ' Finally executes because corresponding Try executed 140 Finally 141 Console.WriteLine("Finally executed in ThrowException") 142 143 End Try 144 145 ' any code placed here is never reached 146 147 End Sub' ThrowExceptionCatchRethrow 148 149 End Class' UsingExceptions UsingExceptions.vb Calling DoesNotThrowException In DoesNotThrowException Finally executed in DoesNotThrowException End of DoesNotThrowException Calling ThrowExceptionWithCatch In ThrowExceptionWithCatch Message: Exception in ThrowExceptionWithCatch Finally executed in ThrowExceptionWithCatch End of ThrowExceptionWithCatch Calling ThrowExceptionWithoutCatch In ThrowExceptionWithoutCatch Finally executed in ThrowExceptionWithoutCatch Caught exception from ThrowExceptionWithoutCatch in Main Calling ThrowExceptionCatchRethrow Method ThrowExceptionCatchRethrow Message: Exception in ThrowExceptionCatchRethrow Finally executed in ThrowException Caught exception from ThrowExceptionCatchRethrow in Main

  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

  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

  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

  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

  23. 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 1 ' Fig. 11.3: Properties.vb 2 ' Stack unwinding and Exception class properties. 3 4 ' demonstrates using properties Message, StackTrace and 5 ' InnerException 6 Class CProperties 7 8Shared Sub Main() 9 10 ' call Method1; any Exception generatesd will be caught 11 ' in the Catch block that follows 12 Try 13 Method1() 14 15 ' Output String representation of Exception, then output 16 ' values of properties InnerException, Message and StackTrace 17 Catch exception As Exception 18 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 Try 31 32 End Sub' Main 33 Properties.vb

  24. 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 thrownand Convert.ToInt32 is removedfrom the stack The specified exception typematches the type thrown sothe exception is caught The FormatException ispassed to the constructoras an InnerException Method 3 terminatesand unwinding begins 34 ' calls Method2 35 Public Shared Sub Method1() 36 Method2() 37 End Sub 38 39 ' calls Method3 40 Public Shared Sub Method2() 41 Method3() 42 End Sub 43 44 ' throws an Exception containing InnerException 45 Public Shared Sub Method3() 46 47 ' attempt to convert String to Integer 48 Try 49 Convert.ToInt32("Not an integer") 50 51 ' wrap FormatException in new Exception 52Catch formatException As FormatException 53 54Throw New Exception("Exception occurred in Method3", _ 55 formatException) 56 57 End Try 58 59End Sub ' Method3 60 61 End Class' CProperties Properties.vb 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)

  25. 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 Properties.vb

  26. 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 Properties.vb

  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

  28. 1 ' Fig. 11.4: NegativeNumberException.vb 2 ' NegativeNumberException represents exceptions caused by 3 ' illegal operations performed on negative numbers. 4 5 Public Class NegativeNumberException 6 Inherits ApplicationException 7 8 ' default constructor 9 Public Sub New() 10 MyBase.New("Illegal operation for a negative number") 11 End Sub 12 13 ' constructor for customizing error message 14 Public Sub New(ByVal messageValue As String) 15 MyBase.New(messageValue) 16 End Sub 17 18 ' constructor for customizing error message and specifying 19 ' inner exception object 20 Public Sub New(ByVal messageValue As String, _ 21 ByVal inner As Exception) 22 23 MyBase.New(messageValue, inner) 24 End Sub 25 26 End Class' NegativeNumberException NegativeNumberException.vb

  29. If numeric value entered is negative a NegativeNumberException is thrown Method Sqrt of class Math 1 ' Fig. 11.5: SquareRootTest.vb 2 ' Demonstrating a user-defined exception class. 3 4 Imports System.Windows.Forms 5 6 Public Class FrmSquareRoot 7 Inherits Form 8 9 ' Label for showing square root 10 Friend WithEvents lblOutput As Label 11 Friend WithEvents lblInput As Label 12 13 ' Button invokes square-root calculation 14 Friend WithEvents cmdSquareRoot As Button 15 16 ' TextBox receives user's Integer input 17 Friend WithEvents txtInput As TextBox 18 19 ' Windows Form Designer generated code 20 21 ' computes square root of parameter; throws 22 ' NegativeNumberException if parameter is negative 23 Public Function SquareRoot(ByVal operand As Double) As Double 24 25 ' if negative operand, throw NegativeNumberException 26 If operand < 0Then 27Throw New NegativeNumberException( _ 28 "Square root of negative number not permitted") 29 30 End If 31 32 ' compute square root 33Return Math.Sqrt(operand) 34 35 End Function' cmdSquareRoot SquareRootTest.vb

  30. 36 37 ' obtain user input, convert to double and calculate square root 38 Private Sub cmdSquareRoot_Click( _ 39 ByVal sender As System.Object, _ 40 ByVal e As System.EventArgs) Handles cmdSquareRoot.Click 41 42 lblOutput.Text = "" 43 44 ' catch any NegativeNumberException thrown 45 Try 46 Dim result As Double = _ 47 SquareRoot(Convert.ToDouble(txtInput.Text)) 48 49 lblOutput.Text = result.ToString() 50 51 ' process invalid number format 52 Catch formatException As FormatException 53 MessageBox.Show(formatException.Message, _ 54 "Invalid Number Format", MessageBoxButtons.OK, _ 55 MessageBoxIcon.Error) 56 57 ' diplay MessageBox if negative number input 58 Catch negativeNumberException As NegativeNumberException 59 MessageBox.Show(negativeNumberException.Message, _ 60 "Invalid Operation", MessageBoxButtons.OK, _ 61 MessageBoxIcon.Error) 62 63 End Try 64 65 EndSub' cmdSquareRoot_Click 66 67 End Class' FrmSquareRoot SquareRootTest.vb

  31. SquareRootTest.vb

  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

  33. 1 ' Fig. 11.6: Overflow.vb 2 ' Demonstrating overflows with and without checking. 3 4 ' demonstrates overflows with and without checking 5 Class COverflow 6 7 Shared Sub Main() 8 9 ' calculate sum of number1 and number 2 10 Try 11 12 Dim number1 As Integer = Int32.MaxValue' 2,147,483,647 13 Dim number2 As Integer = Int32.MaxValue' 2,147,483,647 14 Dim sum As Integer = 0 15 16 ' output numbers 17 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 sum 24 25 ' this statement will not throw OverflowException if user 26 ' removes integer-overflow checks 27 Console.WriteLine(vbCrLf & _ 28 "Sum after operation: {0}", sum) 29 30 ' catch overflow exception 31 Catch exceptionInformation As OverflowException 32 Console.WriteLine(exceptionInformation.ToString()) 33 34 End Try 35 Overflow.vb

  34. 36 End Sub' Main 37 38 End Class' COverflow Overflow.vb number1: 2147483647 number2: 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: 2147483647 number2: 2147483647 Sum integers in checked context: Sum after operation: -2

More Related