 2002 Prentice Hall. All rights reserved. 1 Chapter 11 – Exception Handling Outline 11.1Introduction 11.2 Exception Handling Overview 11.3 Example: DivideByZeroException.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Error-handling using exceptions
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
Try…Catch…Finally Blocks ( continued ) Generic catch clause –Omit argument list with the catch –Any exception thrown is handled by executing code within.
C# Programming: From Problem Analysis to Program Design1 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design 3 rd.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Chapter 11 Debugging and Handling Exceptions
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Exception Handling: A Deeper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Handling Errors during the Program Execution Svetlin Nakov Telerik Corporation
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
Chapter 15 Strings String::Concat String::CompareTo, Equals, == If( string1 == S”Hello”) String1->Equals(S”Hello”) String1->CompareTo(S”Hello”) CompareTo.
 2002 Prentice Hall. All rights reserved. 1 Chapter 11 – Exception Handling Outline 11.1 Introduction 11.2 Exception Handling Overview 11.3 Example: DivideByZeroException.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
 2009 Pearson Education, Inc. All rights reserved Exception Handling Many slides modified by Prof. L. Lilien (even many without explicit message).
Chapter 12: Advanced Topics: Exception Handling Visual Basic.NET Programming: From Problem Analysis to Program Design.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
 2002 Prentice Hall. All rights reserved. 1 Chapter 11 – Exception Handling Outline 11.1 Introduction 11.2 Exception Handling Overview 11.3 Example: DivideByZeroException.
 2009 Pearson Education, Inc. All rights reserved Exception Handling.
J. Goetz,  Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics.
Dr. Abraham. Exception Any problem that VB or OS could not handle Robust program A program that performs well not only under ordinary conditions but also.
 2002 Prentice Hall. All rights reserved. 1 Exception Handling Overview Exception handling –Enable clear, robust and more fault-tolerant programs –Process.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Object Oriented Programming
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: Exception Handling Tujuan Instruksional Khusus: Mahasiswa dapat.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
VB.Net - Exceptions Copyright © Martin Schray
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions, handling exceptions & message boxes Year 11 Information Technology.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 23 - Exception Handling Outline 23.1Introduction.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
Exception Handling Outline 23.1 Introduction
Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University
Exception Handling How to handle the runtime errors.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
Lecture 11 Dr. Eng. Ibrahim El-Nahry Exception Handling.
Chapter 11 – Exception Handling
16 Exception Handling.
Chapter 14 – Exception Handling
Debugging and Handling Exceptions
Chapter 14: Exception Handling
Chapter 12 – Exception Handling
CNS 3260 C# .NET Software Development
Exception Handling Chapter 9 Edited by JJ.
Chapter 15 – Exception Handling
Presentation transcript:

 2002 Prentice Hall. All rights reserved. 1 Chapter 11 – Exception Handling Outline 11.1Introduction 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

 2002 Prentice Hall. All rights reserved Introduction Exception –Indication of problem during program’s execution –Although problem can occur, it occurs infrequently

 2002 Prentice Hall. All rights reserved 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 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 Exception Handling Overview Try block –Encloses code in which errors may occur

 2002 Prentice Hall. All rights reserved 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 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. Outline 8 DivideByZeroTest.vb 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 ' label and TextBox for specifying denominator 14 Friend WithEvents lblDenominator As Label 15 Friend WithEvents txtDenominator As TextBox ' button for dividing numerator by denominator 18 Friend WithEvents cmdDivide As Button Friend WithEvents lblOutput As Label ' output for division ' Windows Form Designer generated code ' 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 lblOutput.Text = "" ' retrieve user input and call Quotient 31 Try 32 Keyword Try indicates beginning of Try block Try block encloses code in which errors may occur

 2002 Prentice Hall. All rights reserved. Outline 9 DivideByZeroTest.vb 33 ' Convert.ToInt32 generates FormatException if argument 34 ' is not an integer 35 Dim numerator As Integer = _ 36 Convert.ToInt32(txtNumerator.Text) Dim denominator As Integer = _ 39 Convert.ToInt32(txtDenominator.Text) ' division generates DivideByZeroException if 42 ' denominator is 0 43 Dim result As Integer = numerator \ denominator lblOutput.Text = result.ToString() ' process invalid number format 48 Catch formattingException As FormatException 49 MessageBox.Show("You must enter two integers", _ 50 "Invalid Number Format", MessageBoxButtons.OK, _ 51 MessageBoxIcon.Error) ' 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) End Try End Sub ' cmdDivide_Click End Class ' FrmDivideByZero If either exception occurs the Try block expires The appropriate error message dialog is displayed for the user Type of exception that the Catch block can handle If the denominator is zero the CLR throws a DivideByZeroException

 2002 Prentice Hall. All rights reserved. Outline 10 DivideByZeroTest.vb

 2002 Prentice Hall. All rights reserved 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 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 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. Outline 14 UsingExceptions. vb 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() ' Case 2: Exception occurs and is caught in called method 15 Console.WriteLine(vbCrLf & _ 16 "Calling ThrowExceptionWithCatch") ThrowExceptionWithCatch() ' Case 3: Exception occurs, but not caught in called method 21 ' because no Catch block. 22 Console.WriteLine(vbCrLf & _ 23 "Calling ThrowExceptionWithoutCatch") ' call ThrowExceptionWithoutCatch 26 Try 27 ThrowExceptionWithoutCatch() ' process exception returned from ThrowExceptionWithoutCatch 30 Catch 31 Console.WriteLine("Caught exception from " & _ 32 "ThrowExceptionWithoutCatch in Main") End Try 35 Main invokes method DoesNotThrowException Main invokes method ThrowExceptionWithCatch Main invokes method ThrowExceptionWithoutCatch Try block enables Main to catch any exceptions thrown by ThrowExceptionWithoutCatch

 2002 Prentice Hall. All rights reserved. Outline 15 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") ' call ThrowExceptionCatchRethrow 42 Try 43 ThrowExceptionCatchRethrow() ' process exception returned from ThrowExceptionCatchRethrow 46 Catch 47 Console.WriteLine("Caught exception from " & _ 48 "ThrowExceptionCatchRethrow in Main") End Try End Sub ' Main ' no exceptions thrown 55 Public Shared Sub DoesNotThrowException() ' Try block does not throw any exceptions 58 Try 59 Console.WriteLine("In DoesNotThrowException") ' this Catch never executes 62 Catch 63 Console.WriteLine("This Catch never executes") ' Finally executes because corresponding Try executed 66 Finally 67 Console.WriteLine( _ 68 "Finally executed in DoesNotThrowException") End Try Program control ignores Catch handler because the Try block does not throw an exception Finally block executes displaying a message Methods are Shared so Main can invoke them directly Try block enables Main to catch any exceptions thrown by ThrowExceptionCatchRethrow Main invokes method ThrowExceptionCatchRethrow

 2002 Prentice Hall. All rights reserved. Outline 16 UsingExceptions. vb Console.WriteLine("End of DoesNotThrowException") 73 End Sub ' DoesNotThrowException ' throws exception and catches it locally 76 Public Shared Sub ThrowExceptionWithCatch() ' Try block throws exception 79 Try 80 Console.WriteLine("In ThrowExceptionWithCatch") Throw New Exception( _ 83 "Exception in ThrowExceptionWithCatch") ' catch exception thrown in Try block 86 Catch exception As Exception 87 Console.WriteLine("Message: " & exception.Message) ' Finally executes because corresponding Try executed 90 Finally 91 Console.WriteLine( _ 92 "Finally executed in ThrowExceptionWithCatch") End Try Console.WriteLine("End of ThrowExceptionWithCatch") 97 End Sub ' ThrowExceptionWithCatch ' throws exception and does not catch it locally 100 Public Shared Sub ThrowExceptionWithoutCatch() ' throw exception, but do not catch it 103 Try 104 Console.WriteLine("In ThrowExceptionWithoutCatch") 105 DoesNotThrowException ends and program control returns to Main Try block creates an exception object and uses Throw statement to throw the object This string becomes the exception object’s error message and the Try block expires ThrowExceptionWithCatch ends and program control returns to Main Finally block executes displaying a message The specified exception type matches the type thrown so the exception is caught and a message is displayed Program control continues at first Catch handler following the Try

 2002 Prentice Hall. All rights reserved. Outline 17 UsingExceptions. vb 106 Throw New Exception( _ 107 "Exception in ThrowExceptionWithoutCatch") ' Finally executes because corresponding Try executed 110 Finally 111 Console.WriteLine("Finally executed in " & _ 112 "ThrowExceptionWithoutCatch") End Try ' unreachable code; would generate syntax error End Sub ' ThrowExceptionWithoutCatch ' throws exception, catches it and rethrows it 121 Public Shared Sub ThrowExceptionCatchRethrow() ' Try block throws exception 124 Try 125 Console.WriteLine("Method ThrowExceptionCatchRethrow") Throw New Exception( _ 128 "Exception in ThrowExceptionCatchRethrow") ' catch any exception, place in object error 131 Catch exception As Exception 132 Console.WriteLine("Message: " & exception.Message) ' rethrow exception for further processing 135 Throw exception ' unreachable code; would generate syntax error 138 Exception is not caught because there are no catch handlers Finally block executes displaying a message Program control returns to Main where the exception is caught Exception is caught and rethrown

 2002 Prentice Hall. All rights reserved. Outline 18 UsingExceptions. vb 139 ' Finally executes because corresponding Try executed 140 Finally 141 Console.WriteLine("Finally executed in ThrowException") End Try ' any code placed here is never reached End Sub ' ThrowExceptionCatchRethrow End Class ' UsingExceptions 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 Program control returns to Main where the exception is caught Finally block executes displaying a message

 2002 Prentice Hall. All rights reserved 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 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 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 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. Outline 23 Properties.vb 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 8 Shared Sub Main() 9 10 ' call Method1; any Exception generatesd will be caught 11 ' in the Catch block that follows 12 Try 13 Method1() ' 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()) Console.WriteLine("exception.Message: " & _ 22 vbCrLf & "{0}" & vbCrLf, exception.Message) Console.WriteLine("exception.StackTrace: " & _ 25 vbCrLf & "{0}" & vbCrLf, exception.StackTrace) Console.WriteLine("exception.InnerException: " & _ 28 vbCrLf & "{0}" & vbCrLf, exception.InnerException) End Try End Sub ' Main 33 Invocation of Main, which becomes the first method on the method-call stack Main invokes Method 1, which becomes the second method on the method-call stack Exception is caught by catch handler

 2002 Prentice Hall. All rights reserved. Outline 24 Properties.vb 34 ' calls Method2 35 Public Shared Sub Method1() 36 Method2() 37 End Sub ' calls Method3 40 Public Shared Sub Method2() 41 Method3() 42 End Sub ' throws an Exception containing InnerException 45 Public Shared Sub Method3() ' attempt to convert String to Integer 48 Try 49 Convert.ToInt32("Not an integer") ' wrap FormatException in new Exception 52 Catch formatException As FormatException Throw New Exception("Exception occurred in Method3", _ 55 formatException) End Try End Sub ' Method 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 method Convert.ToInt32 Because the argument is not in Integer format an exception is thrown and Convert.ToInt32 is removed from the stack The specified exception type matches the type thrown so the exception is caught The FormatException is passed to the constructor as an InnerException Method 3 terminates and unwinding begins

 2002 Prentice Hall. All rights reserved. Outline 25 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 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. Outline 26 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 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. Outline 28 NegativeNumberEx ception.vb 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 ' constructor for customizing error message 14 Public Sub New(ByVal messageValue As String) 15 MyBase.New(messageValue) 16 End Sub ' constructor for customizing error message and specifying 19 ' inner exception object 20 Public Sub New(ByVal messageValue As String, _ 21 ByVal inner As Exception) MyBase.New(messageValue, inner) 24 End Sub End Class ' NegativeNumberException

 2002 Prentice Hall. All rights reserved. Outline 29 SquareRootTest.v b 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 ' Button invokes square-root calculation 14 Friend WithEvents cmdSquareRoot As Button ' TextBox receives user's Integer input 17 Friend WithEvents txtInput As TextBox ' Windows Form Designer generated code ' computes square root of parameter; throws 22 ' NegativeNumberException if parameter is negative 23 Public Function SquareRoot(ByVal operand As Double) As Double ' if negative operand, throw NegativeNumberException 26 If operand < 0 Then 27 Throw New NegativeNumberException( _ 28 "Square root of negative number not permitted") End If ' compute square root 33 Return Math.Sqrt(operand) End Function ' cmdSquareRoot If numeric value entered is negative a NegativeNumberException is thrown Method Sqrt of class Math

 2002 Prentice Hall. All rights reserved. Outline 30 SquareRootTest.v b ' 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 lblOutput.Text = "" ' catch any NegativeNumberException thrown 45 Try 46 Dim result As Double = _ 47 SquareRoot(Convert.ToDouble(txtInput.Text)) lblOutput.Text = result.ToString() ' process invalid number format 52 Catch formatException As FormatException 53 MessageBox.Show(formatException.Message, _ 54 "Invalid Number Format", MessageBoxButtons.OK, _ 55 MessageBoxIcon.Error) ' diplay MessageBox if negative number input 58 Catch negativeNumberException As NegativeNumberException 59 MessageBox.Show(negativeNumberException.Message, _ 60 "Invalid Operation", MessageBoxButtons.OK, _ 61 MessageBoxIcon.Error) End Try End Sub ' cmdSquareRoot_Click End Class ' FrmSquareRoot

 2002 Prentice Hall. All rights reserved. Outline 31 SquareRootTest.v b

 2002 Prentice Hall. All rights reserved 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. Outline 33 Overflow.vb 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 Dim number1 As Integer = Int32.MaxValue ' 2,147,483, Dim number2 As Integer = Int32.MaxValue ' 2,147,483, Dim sum As Integer = ' output numbers 17 Console.WriteLine("number1: {0}" & vbCrLf & _ 18 "number2: {1}", number1, number2) Console.WriteLine(vbCrLf & _ 21 "Sum integers in checked context:") sum = number1 + number2 ' compute sum ' this statement will not throw OverflowException if user 26 ' removes integer-overflow checks 27 Console.WriteLine(vbCrLf & _ 28 "Sum after operation: {0}", sum) ' catch overflow exception 31 Catch exceptionInformation As OverflowException 32 Console.WriteLine(exceptionInformation.ToString()) End Try 35

 2002 Prentice Hall. All rights reserved. Outline 34 Overflow.vb 36 End Sub ' Main End Class ' COverflow number1: number2: 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: number2: Sum integers in checked context: Sum after operation: -2