Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012

Similar documents
Errors and Exceptions

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

1: Introduction to Object (1)

Object Oriented Programming Exception Handling

Exceptions in Java

Debugging Your Python Code: For Dummies

Exception Handling in C++

The compiler is spewing error messages.

11Debugging and Handling. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Assertions and Exceptions Lecture 11 Fall 2005

Part I: Programming Access Applications. Chapter 1: Overview of Programming for Access. Chapter 2: Extending Applications Using the Windows API

Programming II (CS300)

CS 3 Introduction to Software Engineering. 3: Exceptions

Macros & Streams Spring 2018 Discussion 9: April 11, Macros

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

CS125 : Introduction to Computer Science. Lecture Notes #11 Procedural Composition and Abstraction. c 2005, 2004 Jason Zych

It s possible to get your inbox to zero and keep it there, even if you get hundreds of s a day.

These are notes for the third lecture; if statements and loops.

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Reliable programming

Text Input and Conditionals

Debugging and Handling Exceptions

CS450: Structure of Higher Level Languages Spring 2018 Assignment 7 Due: Wednesday, April 18, 2018

Chapter01.fm Page 1 Monday, August 23, :52 PM. Part I of Change. The Mechanics. of Change

Heuristic Evaluation of Team Betamax

Programming II (CS300)

Data Structures. 02 Exception Handling

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

A Comparison of Unified Parallel C, Titanium and Co-Array Fortran. The purpose of this paper is to compare Unified Parallel C, Titanium and Co-

Exceptions and Design

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Intro. Scheme Basics. scm> 5 5. scm>

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

How to Get Your Inbox to Zero Every Day

Taskbar: Working with Several Windows at Once

It d really be nice if all the scripts you write work flawlessly each and

An Introduction to Python

6.001 Notes: Section 17.5

Rescuing Lost Files from CDs and DVDs

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Proofwriting Checklist

Exceptions in Erlang - Redux

Exception Handling. Chapter 8. Chapter 8 1

Divisibility Rules and Their Explanations

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Client Code - the code that uses the classes under discussion. Coupling - code in one module depends on code in another module

Under the Debug menu, there are two menu items for executing your code: the Start (F5) option and the

ECE 122. Engineering Problem Solving with Java

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Errors. Lecture 6. Hartmut Kaiser hkaiser/fall_2011/csc1254.html

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

CS Introduction to Data Structures How to Parse Arithmetic Expressions

Software Design and Analysis for Engineers

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

IS 0020 Program Design and Software Tools

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Chapter 5 Errors. Bjarne Stroustrup

12/14/2016. Errors. Debugging and Error Handling. Run-Time Errors. Debugging in C# Debugging in C# (continued)

Program Correctness and Efficiency. Chapter 2

Algorithms in Systems Engineering IE172. Midterm Review. Dr. Ted Ralphs

FUNCTIONS. The Anatomy of a Function Definition. In its most basic form, a function definition looks like this: function square(x) { return x * x; }

Chapter 11: Exception Handling

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

If Statements, For Loops, Functions

CS 370 The Pseudocode Programming Process D R. M I C H A E L J. R E A L E F A L L

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15


CATCH Me if You Can Doug Hennig

Lecture 9: July 14, How to Think About Debugging

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage

Civil Engineering Computation

Table of Laplace Transforms

Excel programmers develop two basic types of spreadsheets: spreadsheets

Object Oriented Programming

6.001 Notes: Section 4.1

How to approach a computational problem

First-Order Translation Checklist

How to Rescue a Deleted File Using the Free Undelete 360 Program

15-498: Distributed Systems Project #1: Design and Implementation of a RMI Facility for Java

B l o c k B i n d i n g s

Programming and Data Structure

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup.

Exceptions. Examples of code which shows the syntax and all that

This book is about using Visual Basic for Applications (VBA), which is a

Errors. And How to Handle Them

Visual Basic 2008 Anne Boehm

Notes on Non-Chronologic Backtracking, Implication Graphs, and Learning

Chapter 2.6: Testing and running a solution

(Refer Slide Time: 01.26)

Traditional Error Handling

Stage 11 Array Practice With. Zip Code Encoding

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

3 Nonlocal Exit. Quiz Program Revisited

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

After completing this appendix, you will be able to:

(Refer Slide Time 6:48)

Transcription:

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012 1 Objective To understand why exceptions are useful and why Visual Basic has them To gain experience with exceptions and exception handling To learn best practices in exception handling 2 Errors and Error handling So far, we assume that our users are not malicious and will provide our programs with sensible input. When we ask for an integer, we assume that the user will provide an integer and not a string (though we ve seen that if you do provide a string, things break horribly). When we don t enter an integer when our program is expecting one, Visual Studio stops executing our program and tells us that it has found an uncaught exception and highlights the line number in our program that caused this exception. To this point, we have avoided having to deal with unexpected input by only entering the types of input our program is expecting. When we are using Visual Studio, this isn t terrible because we can see where the program broke and simply fix the issue and restart it. However, wehen we deploy our programs, they will run without the Visual Studio environment and an uncaught exception will cause the program to crash without any indication of where or why. We have all had this happen to us, so we all know the frustration we feel when a program crashes. However, real-world programs (for the most part) are resilient to users providing incorrect input, and in fact there are statistics that show more than half of all code written is error-handling code. In order to accomplish this, there are generally two schools of thought: test conditions to make sure all the inputs to a program or subprocess (e.g.: subroutine or function) are valid before entering the subprocess, or attempt to execute the subprocess with the inputs available and recovering if something breaks. Both strategies have their advantages, but Visual Basic is mostly in the latter camp. 2.1 Handling errors using normal control flow Earlier in the course, we saw If statements. If statements are one way of checking for errors and handling them before they would cause a problem. This method of error checking allows us to handle an incorrect input early, perhaps before we try to use it in several subprocesses. However, in order to prevent errors altogether, we would need an exhaustive set of If statements to handle (almost) every possible error condition. This gets time consuming and requires mind-bogglingly many lines of code. In addition, since Visual Basic uses exceptions heavily in the built-in functions and framework methods, if failing to prevent an error condition will still result in an uncaught exception and Visual Studio will stop your program. That doesn t mean that there is not a right place for pre-emptive error handling; an example is shown below. If divisor <> 0 Then quotient = dividend / divisor txtresult.text = "The quotient is " & quotient Else txtresult.text = "Can not divide by zero" 1

The equivalent code using structured exception handling would look like quotient = dividend / divisor txtresult.text = "The quotient is " & quotient Catch ex As DivideByZeroException txtresult.text = "Can not divide by zero" End There seems to be very little benefit to using If statements over exceptions in this case, but since the condition to check for is very simple (and the likelihood that we are only using it to be the divisor in a single calculation is very small) we might as well just use the If statement. In addition, error handling should be readable. With the If statement, it is very clear what could cause the divide-by-zero condition. The exception handling code obscures this and makes the code difficult to understand. 2.2 Why exceptions make error handling easier That said, structured exception handling does make life easier. Usually, it covers for the fact that the set of all possible errors is very large and sometimes very elusive. We don t necessarily know exactly why an error occurred or perhaps even where it occurred. For instance, let s assume that there are other possibilities for errors in our code above, but we either don t know exactly what they are, exactly how to test them, or both. We can expand the... Catch statement to handle additional cases: quotient = dividend / divisor txtresult.text = "The quotient is " & quotient Catch ex As DivideByZeroException txtresult.text = "Can not divide by zero" Catch ex As Exception txtresult.text = "Something unanticipated occurred" End In addition, when dealing with parts of the computer outside of our program s control, it makes more sense to try to perform some operation and then recover if the operation failed. For example, consider a network connection. If our code first checks to ensure the network connection is active, then tries to send data across, there is a distinct possibility that the network connection could drop after we check it, but before we use it. Since Visual Basic s network utilities use exceptions heavily, we will not prevent an unhandled exception from occurring. Network connections provide an example of another excellent reason to use structured exception handling. Often, we would want to do multiple things with a network connection at one time to facilitate communication. Checking the connection to make sure that it is ready for us to use it every time would be unreadable, redundant, and tedious to write. If we checked once and then hoped everything afterward worked, we would still not be preventing exceptions from happening. However, we can group these operations together into a single... Catch block to handle the errors all at once, without having to know exactly what will cause the error or exactly where it will occur. This is demonstrated in pseudo-vb below. conn.open() conn.send("hello") Dim response As String = conn.receive() conn.send(response) response = conn.receive() 2

conn.close() txtresult.text = response Catch ex As NetworkException txtresult.text = "Something broke" End The... Catch block has the added benefit that as soon as an exception occurs and is caught, no more statements in the section are executed and execution immediately jumps to the Catch block (or the appropriate Catch block to handle the exception if there are more than one). 3 Handling Exceptions Most often, what you will do is handle exceptions that occur in code you are calling. When an exception occurs, we say that it has been thrown. We have already seen some exceptions get thrown by code we are calling when we, for instance, attempt to enter the string ten when we are asking for an integer (e.g. 10 ). Visual Basic recognizes that this is an undefined state that it does not know how to recover from, so it throws an exception. This breaks outside of the normal flow of execution and bubbles up the call stack until something handles it (if there is nothing to handle it, Visual Studio stops your program with the unhandled exception message), meaning that code that calls functions that throw exceptions does not have to explicitly pass error conditions back to the code that called it (as would be the case with simple If statements) because this is done automatically. In order to handle exceptions, we have to determine what exception we want to handle (and in order to know that, we need to know what an exception is) and we need to learn some syntax. 3.1 What is an Exception? Semantically, an exception is a thing. It has attributes (like what caused it, when, where, etc.) and operations (like getting a lower-level exception that caused the current exception), just like any other thing in Visual Basic, which are called objects. Objects are explained in greater detail later on, but for now the important concept is that Exceptions are not arbitrary pieces of text. They are specifically defined by Visual Basic (actually, by the.net framework) and are therefore able to be used in our code. There is also a hierarchy of these exceptions, which allows us to have multiple Catch blocks (like in the third example) to catch several different types of exceptions at various levels on the hierarchy, including a catch-all (similar to an Else or Case Else) by catching Exception, the top of the hierarchy. 3.2 Anatomy of... Catch The easiest way to describe the anatomy of the... Catch block is to show the most verbose variation and then explain the parts and whether they are required or optional. Code that may throw an exception Catch <identifier> As <ExceptionType1> Code to catch exception of type 1 Catch <identifier> As <ExceptionType2> Code to catch exception of type 2 Catch <identifier> As Exception Code to catch all other exceptions Finally Code to execute regardless of error condition End 3

The and End parts are required and form the bounds of the block. In addition, at least one Catch part is required. This can either catch a specific exception or the highest-level Exception type. Each Catch block can use the same identifier, since each will exist within its own scope, or you can use a different identifier for each to help keep the sections readable. No more than one catch statement can catch the same type of exception within the same... Catch block. If you have multiple Catch lines, the exception types that are higher in the exception hierarchy should be listed lower, as the first one that matches the exception will be used to handle the exception. This means that if Catch ex As Exception is first, it will always be used to handle any exception, even if more specific exceptions are listed further down. The Finally block is a little different and I have actually never used one. Code in this block always gets executed, regardless of whether there is an error condition in the block. This is different from having code outside the... Catch altogether in that the scope is a continuation of the block. That means that if, for instance, a resource is put into a particular state that needs to be restored regardless of whether the operation has failed (and this state change will not cause an exception), the state restoration code should go in the Finally clause so it is always executed. 4 Throwing Exceptions Catching exceptions is all well and good when you are calling off to built-in Visual Basic code, but exception handling as a strategy is not the most useful unless you can also throw your own. In the simple programs we ve written so far, throwing exceptions wouldn t do us a whole lot of good, but now that we have functions and subroutines at our disposal, using exceptions to forgo executing moot code on an error is something that makes our code much more readable and allows us to avoid nasty If statements all over the place. The syntax to throw an exception is straightforward: Throw New Exception Since an exception is an object (as described above), with its own attributes and methods, we use the New keyword to create a new exception to describe this particular instance. The Throw keyword indicates that execution of the program should stop following its normal path and look for an exception handler of the given type. In this case, the exception is the highest-level general Exception, but it could just as easily be something more specific, like DivideByZeroException or SocketException. This statement can be placed at any point in a method and is usually in response to an expected error condition. For instance, if we assume that LessThanZeroException exists, we can write a function for doing factorials like this: Public Function Factorial(ByVal i As Integer) As Long If i < 0 Then Throw New LessThanZeroException If i = 0 Then Return 1 Return i * Factorial(i - 1) End Function 5 Best Practices Like all best practices, these are simply guidelines. Every note here is based on something I have seen in real live code. Sometimes the programmer had good reason to use style that might otherwise be 4

considered poor programming, but most of the time it was just poor programming. I will point out when violating the best practices may actually be useful. 5.1 Length of code to try and catch Code in a block should be short and the code to handle the exception should also be short. In general, the code that is in the try block should be one line or statement; that is, only the line of code that may cause an exception. If several lines may throw the same or similar exceptions, it is acceptable to group them together in the same... Catch block for readability and to avoid repeating code. It is far from acceptable to group together two statements or groups of statements that throw two different types of exceptions in the same with the two separate exceptions enumerated in individual Catch blocks as below. statement 1, throws exception A statement 2, throws exception B Catch ex As ExceptionA handle exception A Catch ex As ExceptionB handle exception B End This should be broken out into two different... Catch blocks. Likewise, the code blocks to handle exceptions should be short. The... Catch structure is not a method of performing a decision like If and Select [Case], but a way to handle errors. Your exception-handling code should do something based on the error in one or two lines and then be done. Usually this involves recording the error somehow. 5.2 Throwing or handling, not both One block of code should either throw an exception or catch an exception, but should not do both. Code that does both takes one of the two following forms (not real Visual Basic): 5.2.1 Throwing an exception just to catch it If Not conn.connected Then Throw New NetworkException txtresult.text = "Connected" Catch ex As NetworkException txtresult.text = "Not connected" End Usually this case would not be as short as this example, so it wouldn t be as obvious, but it doesn t mean it is any more acceptable. A case like this could easily be handled using an If statement or similar, as below: If Not conn.connected Then txtresult.text = "Not connected" Else txtresult.text = "Connected" 5

5.2.2 Throwing an exception from a Catch block statement that throws ExceptionA Catch ex As ExceptionA Throw ExceptionB End Words can t even begin to describe how bad this is. Code should either handle an exception or not handle an exception. It shouldn t handle one exception just to turn it into a different exception and pass that new exception on up the call stack. This not only passes the buck, but also hides the original cause of the error from the calling code. This makes things more difficult to debug and makes it difficult to provide useful feedback to a user. 5.3 Empty Catch blocks The whole theme here is that the Catch block is used to do something when an error condition occurs. If you don t do anything when you handle the exception, all you are doing is hiding the fact that an error occurred. Sometimes this is the desired effect (I have done this before when I m really just testing if I can do something), but most of the time this is laziness. I have spent hours debugging code that did not crash, but also did not function, only to find that the failure was being hidden because the exception was being caught by an empty Catch block. To make a long story short, avoid empty Catch blocks at all costs. 6