
Structured Exception Handling in Visual Basic
Learn how to effectively handle exceptions in Visual Basic by exploring the Exception hierarchy, using Try-Catch statements, throwing exceptions, and implementing structured exception handlers to prevent program termination. Gain insights into common types of data validation and the importance of handling exceptions to ensure software reliability.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
Lecture Set 8 Validating Data and Handling Exceptions Part B Structured Exception Handling
Objectives To understand how to us the Structured Exception handling tools of Visual Basic Describe the Exception hierarchy and name two of its subclasses. Describe the use of Try Catch statements to catch specific exceptions as well as all exceptions. Learn how to throw exceptions and how to catch them and take appropriate steps to prevent software failure 3/21/2025 1:31 PM
Objectives (continued) Describe the use of the properties and methods of an exception object. Describe the use of Throw statements. Describe the three types of data validation that you re most likely to perform on a user entry. Describe two ways that you can use generic validation methods in a method that validates all of the user entries for a form. Describe the use the Validating event and the use of masked text boxes for data validation. 3/21/2025 1:31 PM
Structured Exception Handling Run-time errors will cause a program to terminate because of an exception being thrown Exceptions can be thrown for several reasons Numeric overflow errors Type conversion errors Division by zero errors Database errors of all sorts Null reference exceptions Create structured exception handlers to prevent a program from terminating 3/21/2025 1:31 PM
The Exception Class Hierarchy 3/21/2025 1:31 PM
The Exception Hierarchy for Five Common Exceptions (related to computation ONLY) System namespace Exception FormatException ArithmeticException InvalidCastException OverflowException DivideByZeroException
Why are Unhandled Exceptions Bad? In a nutshell software that fails for any reason is unacceptable Software has to be written to accept any input from the user (or from external events) and react appropriately 3/21/2025 1:31 PM
The Dialog Box for an Unhandled Exception 3/21/2025 1:31 PM
The System.Exception Class All exceptions are derived from the System.Exception class Properties The Message property contains an informational message The Source property is a string containing the name of the application causing the error The StackTrace property returns a string containing the error location 3/21/2025 1:31 PM
Do We Need Structured Exception Handling? Can t we program without this? Can t we program without structured alternatives and repetitions Can t we program without classes? Can t we program without validation structures and tools? Can t I write good code without having to worry about the accessibility of my data? Advantages to having all this structured stuff 3/21/2025 1:31 PM
The Syntax for a Simple Try...Catch statement Syntax try trystatements block catch catchstatements block A Try...Catch statement try { subtotal = ToDecimal(txtSubtotal.Text); discountPercent = .2m; discountAmount = subtotal * discountPercent; invoiceTotal = subtotal - discountAmount; } catch { MessageBox.Show( "Please enter a valid number for the " + "Subtotal field.", "Entry Error"); } 3/21/2025 1:31 PM
The Dialog Box thats Displayed if an Exception Occurs 3/21/2025 1:31 PM
Try-Catch (Another example) private void btnGetWord_Click(object sender, EventArgs e) { btnGetWord.Enabled = false; failureCount = 0; newWord = Dictionary.getWord(); try { lblLetterNumbers.Visible = true; lblOkay.Visible = true; lblLetterNumbers.Text = BuildNewWordTemplate(newWord.Length); } catch { . . . } // end Try-Catch ResetLetters(); } // end GetWord_Click Note that the exception name you choose (ex in this case) is an instantiation of an object of an exception type with properties (such as Message) and methods (such as GetType) associated with it. So what does this code do? 3/21/2025 1:31 PM
The syntax for a Try...Catch statement that accesses the exception try trystatements block catch (exceptionclass exceptionName) catchstatements block 3/21/2025 1:31 PM
Structured Exception Handlers (Syntax) try // Place executable statements that might throw // (cause) an exception in this block. catch // This code runs if the statements in the Try // block throw an exception. finally // This code always runs immediately before // the Try block or Catch block exits. 3/21/2025 1:31 PM
Two Common Properties for all Exceptions It is important to understand how this statement works Property Description Message Gets a message (a string) that briefly describes the current exception. StackTrace Gets a string that lists the procedures that were called before the exception occurred. A common method for all exceptions Method GetType() Description Gets the type of the current exception.
The Complete Syntax for the Try...Catch Statement This form of try-catch includes the specification of exception types try trystatements block catch (mostspecificexception exceptionName) catchstatements block [catch (nextmostspecificexception exceptionName) ... catchstatements block] [catch (leastspecificexception exceptionName) catchstatements block] [finally finallystatements block]
Whats in a Try-Catch Statement? The try block contains the code that may raise (throw) an exception or multiple exceptions The catch block contains the code that actually handles the exception thrown (additional catch blocks may handle additional exceptions) Note that if multiple procedures are called in the try block, the catch block catches all exceptions that are not handled by the called procedures Variables declared within a try catch block are local to that block Code for the most specific exceptions must be placed first and for the least specific exceptions the code comes last 3/21/2025 1:31 PM
Execution Flow of a Structured Exception Handler (VB example) 3/21/2025 1:31 PM
A Try...Catch that Catches Specific Exceptions try { monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text); yearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text); years = Convert.ToInt32(txtYears.Text); months = years * 12; monthlyInterestRate = yearlyInterestRate / 12 / 100; . . . } catch (ExceptionFormat ex) MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString() + "\n" + ex.StackTrace, "Data Entry Other Exception!!"); catch (Exception ex) ... finally // This code runs whether or not an exception occur PerformCleanup(); Note that the exception name you choose (ex in this case) is an instantiation of an object of an exception type with properties (such as Message) and methods (such as GetType) associated with it. So what does this code do?
Notes on the Last Slide Always catch code for the most specific exceptions first. Why? The Finally code block is executed whether the exception occurs and is caught or not The ToDecimal and ToInt32 methods (of the Convert class) do not do any rounding and can lead to FormatExceptions in certain cases This is as opposed to CDec and CInt, the intrinsic functions that do rounding (which can lead to type conversion errors) 3/21/2025 1:31 PM
Throwing Exceptions The syntax for throwing a new exception throw new Exceptionclass ([message]); The syntax for throwing an existing exception throw ExceptionName; 3/21/2025 1:31 PM
A Function that Throws a FormatException public decimal compute(decimal monthlyInterestRate, int months) { if (monthlyInvestment <= 0) throw new FormatException ("Monthly Investment must be greater than 0."); if (monthlyInterestRate <= 0) throw new FormatException ("Interest Rate must be greater than 0."); . . . } // end compute 3/21/2025 1:31 PM
Throwing Exceptions for Special Purposes Code that throws an Exception for testing purposes try { subtotal = Convert.ToDecimal(txtSubtotal.Text); throw new OverflowException; } catch (Exception ex) MessageBox.Show(ex.Message + \n + \n & ex.GetType().ToString()+ \n + \n & ex.StackTrace, "Exception"); Code that rethrows an exception try Convert.ToDecimal(txtSubtotal.Text); catch (FormatException fe) { txtSubtotal.Select(); throw fe; } // end try-catch 3/21/2025 1:31 PM
When to Throw an Exception When a procedure encounters a situation where it isn t able to complete its task When you want to generate an exception to test an exception handler When you want to catch the exception, perform some processing, and then throw the exception again 3/21/2025 1:31 PM
Code To Validate One Data Entry Item What data validation do you need to perform? Ensure that an entry has been made In other words ensure that the user has not skipped over the item Ensure that the entry is in the proper format Ensure that the entry range is valid Note use of the Select method for a Textbox Moves control back to the given Textbox Where parameters are used, Select also helps the user get things correct by showing what the incorrect entry See also, pp. 200-203 in text 3/21/2025 1:31 PM
Three Functions for Validating Textbox Entries These functions are generic ONLY in the sense that they will work on any Textbox However, the functions that check for Decimal ranges and formats are not generic as to the types of the values whose ranges or formats are to be checked SO beware read the code on pp. 202-205 3/21/2025 1:31 PM
Validating Multiple Entries This material concerns the writing of a function to validate multiple (three in this case) textbox entries on a single form. You can take your choice separate validations for each box or one per form (or worse, one long compound condition) Read pp. 204-209 in text 3/21/2025 1:31 PM