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

Size: px
Start display at page:

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

Transcription

1 Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 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

2 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

3 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

4 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

5 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): 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

6 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

Errors and Exceptions

Errors and Exceptions Exceptions Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception isn t necessarily your fault trying

More information

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

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions Errors and Exceptions Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception is a problem whose cause is outside

More information

1: Introduction to Object (1)

1: Introduction to Object (1) 1: Introduction to Object (1) 김동원 2003.01.20 Overview (1) The progress of abstraction Smalltalk Class & Object Interface The hidden implementation Reusing the implementation Inheritance: Reusing the interface

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

Exceptions in Java

Exceptions in Java Exceptions in Java 3-10-2005 Opening Discussion Do you have any questions about the quiz? What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment?

More information

Debugging Your Python Code: For Dummies

Debugging Your Python Code: For Dummies Debugging Your Python Code: For Dummies Tyler J. Metivier University of Connecticut Dept. of Physics May 4, 2018 1 What s the problem? It doesn t matter if you ve written 1 script or programmed a space

More information

Exception Handling in C++

Exception Handling in C++ Exception Handling in C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by

More information

The compiler is spewing error messages.

The compiler is spewing error messages. Appendix B Debugging There are a few different kinds of errors that can occur in a program, and it is useful to distinguish between them in order to track them down more quickly. Compile-time errors are

More information

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

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

More information

Assertions and Exceptions Lecture 11 Fall 2005

Assertions and Exceptions Lecture 11 Fall 2005 Assertions and Exceptions 6.170 Lecture 11 Fall 2005 10.1. Introduction In this lecture, we ll look at Java s exception mechanism. As always, we ll focus more on design issues than the details of the language,

More information

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

Part I: Programming Access Applications. Chapter 1: Overview of Programming for Access. Chapter 2: Extending Applications Using the Windows API 74029c01.qxd:WroxPro 9/27/07 1:43 PM Page 1 Part I: Programming Access Applications Chapter 1: Overview of Programming for Access Chapter 2: Extending Applications Using the Windows API Chapter 3: Programming

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

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

Macros & Streams Spring 2018 Discussion 9: April 11, Macros CS 61A Macros & Streams Spring 2018 Discussion 9: April 11, 2018 1 Macros So far, we ve mostly explored similarities between the Python and Scheme languages. For example, the Scheme list data structure

More information

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

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

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

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur Control Structures Code can be purely arithmetic assignments At some point we will need some kind of control or decision making process to occur C uses the if keyword as part of it s control structure

More information

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

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

More information

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

It s possible to get your  inbox to zero and keep it there, even if you get hundreds of  s a day. It s possible to get your email inbox to zero and keep it there, even if you get hundreds of emails a day. It s not super complicated, though it does take effort and discipline. Many people simply need

More information

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

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

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

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

More information

Reliable programming

Reliable programming Reliable programming How to write programs that work Think about reliability during design and implementation Test systematically When things break, fix them correctly Make sure everything stays fixed

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Debugging and Handling Exceptions

Debugging and Handling Exceptions 12 Debugging and Handling Exceptions C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 1 4th Edition Chapter Objectives Learn about exceptions,

More information

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

CS450: Structure of Higher Level Languages Spring 2018 Assignment 7 Due: Wednesday, April 18, 2018 CS450: Structure of Higher Level Languages Spring 2018 Assignment 7 Due: Wednesday, April 18, 2018 Taken from assignments by Profs. Carl Offner and Ethan Bolker Part 1 - Modifying The Metacircular Evaluator

More information

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

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

More information

Heuristic Evaluation of Team Betamax

Heuristic Evaluation of Team Betamax Heuristic Evaluation of Team Betamax Eric Gallimore Connor Riley Becky Scholl Chris Stone November 4, 2006 Overview Evaluation Let s just state for the record that we like this a whole lot better than

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

Data Structures. 02 Exception Handling

Data Structures. 02 Exception Handling David Drohan Data Structures 02 Exception Handling JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.

More information

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

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information

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-

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- Shaun Lindsay CS425 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- Array Fortran s methods of parallelism

More information

Exceptions and Design

Exceptions and Design Exceptions and Exceptions and Table of contents 1 Error Handling Overview Exceptions RuntimeExceptions 2 Exceptions and Overview Exceptions RuntimeExceptions Exceptions Exceptions and Overview Exceptions

More information

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

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

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

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

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 14: Exceptions 10:00 AM, Feb 26, 2018 Contents 1 Exceptions and How They Work 1 1.1 Update to the Banking Example.............................

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

How to Get Your Inbox to Zero Every Day

How to Get Your Inbox to Zero Every Day How to Get Your Inbox to Zero Every Day MATT PERMAN WHATSBESTNEXT.COM It s possible to get your email inbox to zero and keep it there, even if you get hundreds of emails a day. It s not super complicated,

More information

Taskbar: Working with Several Windows at Once

Taskbar: Working with Several Windows at Once Taskbar: Working with Several Windows at Once Your Best Friend at the Bottom of the Screen How to Make the Most of Your Taskbar The taskbar is the wide bar that stretches across the bottom of your screen,

More information

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

It d really be nice if all the scripts you write work flawlessly each and Bonus Chapter Handling Exceptions In This Chapter Addressing errors the old way Getting to know exceptions Doing something with an exception Generating your own exceptions It d really be nice if all the

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

More information

6.001 Notes: Section 17.5

6.001 Notes: Section 17.5 6.001 Notes: Section 17.5 Slide 17.5.1 Now, let's look at one example in which changing the evaluation model allows us to explore a very different kind of computational problem. Our goal is to show how

More information

Rescuing Lost Files from CDs and DVDs

Rescuing Lost Files from CDs and DVDs Rescuing Lost Files from CDs and DVDs R 200 / 1 Damaged CD? No Problem Let this Clever Software Recover Your Files! CDs and DVDs are among the most reliable types of computer disk to use for storing your

More information

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

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley In Brief: What You Need to Know to Comment Methods in CSE 143 Audience o A random person you don t know who wants

More information

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

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 Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

Proofwriting Checklist

Proofwriting Checklist CS103 Winter 2019 Proofwriting Checklist Cynthia Lee Keith Schwarz Over the years, we ve found many common proofwriting errors that can easily be spotted once you know how to look for them. In this handout,

More information

Exceptions in Erlang - Redux

Exceptions in Erlang - Redux Exceptions in Erlang - Redux Richard Carlsson Uppsala University Björn Gustavsson Patrik Nyblom Ericsson What's the big deal? Exceptions in Erlang are simple, right? Raising exceptions: throw(term) exit(term)

More information

Exception Handling. Chapter 8. Chapter 8 1

Exception Handling. Chapter 8. Chapter 8 1 Exception Handling Chapter 8 Chapter 8 1 Introduction A program can be written assuming that nothing unusual or incorrect will happen. The user will always enter an integer when prompted to do so. There

More information

Divisibility Rules and Their Explanations

Divisibility Rules and Their Explanations Divisibility Rules and Their Explanations Increase Your Number Sense These divisibility rules apply to determining the divisibility of a positive integer (1, 2, 3, ) by another positive integer or 0 (although

More information

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

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

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

Client Code - the code that uses the classes under discussion. Coupling - code in one module depends on code in another module Basic Class Design Goal of OOP: Reduce complexity of software development by keeping details, and especially changes to details, from spreading throughout the entire program. Actually, the same goal as

More information

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

Under the Debug menu, there are two menu items for executing your code: the Start (F5) option and the CS106B Summer 2013 Handout #07P June 24, 2013 Debugging with Visual Studio This handout has many authors including Eric Roberts, Julie Zelenski, Stacey Doerr, Justin Manis, Justin Santamaria, and Jason

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions Overview Problem: Can we detect run-time errors and take corrective action? Try-catch Test for a variety of different program situations

More information

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

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

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

Errors. Lecture 6. Hartmut Kaiser  hkaiser/fall_2011/csc1254.html Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2011/csc1254.html 2 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with

More information

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

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

CS Introduction to Data Structures How to Parse Arithmetic Expressions

CS Introduction to Data Structures How to Parse Arithmetic Expressions CS3901 - Introduction to Data Structures How to Parse Arithmetic Expressions Lt Col Joel Young One of the common task required in implementing programming languages, calculators, simulation systems, and

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 9 Date:

More information

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

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions CSE1720 Click to edit Master Week text 01, styles Lecture 02 Second level Third level Fourth level Fifth level Winter 2015! Thursday, Jan 8, 2015 1 Objectives for this class meeting 1. Conduct review of

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually

More information

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

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there

More information

Chapter 5 Errors. Bjarne Stroustrup

Chapter 5 Errors. Bjarne Stroustrup Chapter 5 Errors Bjarne Stroustrup www.stroustrup.com/programming Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications,

More information

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

12/14/2016. Errors. Debugging and Error Handling. Run-Time Errors. Debugging in C# Debugging in C# (continued) Debugging and Error Handling Debugging methods available in the ID Error-handling techniques available in C# Errors Visual Studio IDE reports errors as soon as it is able to detect a problem Error message

More information

Program Correctness and Efficiency. Chapter 2

Program Correctness and Efficiency. Chapter 2 Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you

More information

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

Algorithms in Systems Engineering IE172. Midterm Review. Dr. Ted Ralphs Algorithms in Systems Engineering IE172 Midterm Review Dr. Ted Ralphs IE172 Midterm Review 1 Textbook Sections Covered on Midterm Chapters 1-5 IE172 Review: Algorithms and Programming 2 Introduction to

More information

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

FUNCTIONS. The Anatomy of a Function Definition. In its most basic form, a function definition looks like this: function square(x) { return x * x; } 2 FUNCTIONS We have already used several functions in the previous chapter things such as alert and print to order the machine to perform a specific operation. In this chapter, we will start creating our

More information

Chapter 11: Exception Handling

Chapter 11: Exception Handling Chapter 11: Exception Handling Understanding Exceptions Exception Any error condition or unexpected behavior in an executing program Exception handling Object-oriented techniques used to manage such errors

More information

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

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet. Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

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

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 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 2 0 1 5 Introduction At this point, you are ready to beginning programming at a lower level How do you actually write your

More information

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

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15 s Computer Science and Engineering College of Engineering The Ohio State University Lecture 15 Throwable Hierarchy extends implements Throwable Serializable Internal problems or resource exhaustion within

More information

» How do I Integrate Excel information and objects in Word documents? How Do I... Page 2 of 10 How do I Integrate Excel information and objects in Word documents? Date: July 16th, 2007 Blogger: Scott Lowe

More information

CATCH Me if You Can Doug Hennig

CATCH Me if You Can Doug Hennig CATCH Me if You Can Doug Hennig VFP 8 has structured error handling, featuring the new TRY... CATCH... FINALLY... ENDTRY structure. This powerful new feature provides a third layer of error handling and

More information

Lecture 9: July 14, How to Think About Debugging

Lecture 9: July 14, How to Think About Debugging Lecture 9: July 14, 2011 How to Think About Debugging So, you wrote your program. And, guess what? It doesn t work. L Your program has a bug in it Somehow, you must track down the bug and fix it Need to

More information

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

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage EECS 183 Week 3 - Diana Gage www-personal.umich.edu/ ~drgage Upcoming Deadlines Lab 3 and Assignment 3 due October 2 nd (this Friday) Project 2 will be due October 6 th (a week from Friday) Get started

More information

Civil Engineering Computation

Civil Engineering Computation Civil Engineering Computation First Steps in VBA Homework Evaluation 2 1 Homework Evaluation 3 Based on this rubric, you may resubmit Homework 1 and Homework 2 (along with today s homework) by next Monday

More information

Table of Laplace Transforms

Table of Laplace Transforms Table of Laplace Transforms 1 1 2 3 4, p > -1 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Heaviside Function 27 28. Dirac Delta Function 29 30. 31 32. 1 33 34. 35 36. 37 Laplace Transforms

More information

Excel programmers develop two basic types of spreadsheets: spreadsheets

Excel programmers develop two basic types of spreadsheets: spreadsheets Bonus Chapter 1 Creating Excel Applications for Others In This Chapter Developing spreadsheets for yourself and for other people Knowing what makes a good spreadsheet application Using guidelines for developing

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch

More information

6.001 Notes: Section 4.1

6.001 Notes: Section 4.1 6.001 Notes: Section 4.1 Slide 4.1.1 In this lecture, we are going to take a careful look at the kinds of procedures we can build. We will first go back to look very carefully at the substitution model,

More information

How to approach a computational problem

How to approach a computational problem How to approach a computational problem A lot of people find computer programming difficult, especially when they first get started with it. Sometimes the problems are problems specifically related to

More information

First-Order Translation Checklist

First-Order Translation Checklist CS103 Winter 2019 First-Order Translation Checklist Cynthia Lee Keith Schwarz In this handout, we ve distilled five specific points that you should check in your first-order logic statements before submitting

More information

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

How to Rescue a Deleted File Using the Free Undelete 360 Program R 095/1 How to Rescue a Deleted File Using the Free Program This article shows you how to: Maximise your chances of recovering the lost file View a list of all your deleted files in the free Restore a

More information

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

15-498: Distributed Systems Project #1: Design and Implementation of a RMI Facility for Java 15-498: Distributed Systems Project #1: Design and Implementation of a RMI Facility for Java Dates of Interest Assigned: During class, Friday, January 26, 2007 Due: 11:59PM, Friday, February 13, 2007 Credits

More information

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

B l o c k B i n d i n g s 1 Block Bindings Traditionally, the way variable declarations work has been one tricky part of programming in JavaScript. In most C-based languages, variables (more formally known as bindings, as a name

More information

Programming and Data Structure

Programming and Data Structure Programming and Data Structure Dr. P.P.Chakraborty Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture # 09 Problem Decomposition by Recursion - II We will

More information

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

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00

More information

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

Chapter 5 Errors. Hyunyoung Lee. Based on slides by Bjarne Stroustrup. Chapter 5 Errors Hyunyoung Lee Based on slides by Bjarne Stroustrup www.stroustrup.com/programming 1 Abstract When we program, we have to deal with errors. Our most basic aim is correctness, but we must

More information

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

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

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

This book is about using Visual Basic for Applications (VBA), which is a In This Chapter Describing Access Discovering VBA Seeing where VBA lurks Understanding how VBA works Chapter 1 Where VBA Fits In This book is about using Visual Basic for Applications (VBA), which is a

More information

Errors. And How to Handle Them

Errors. And How to Handle Them Errors And How to Handle Them 1 GIGO There is a saying in computer science: Garbage in, garbage out. Is this true, or is it just an excuse for bad programming? Answer: Both. Here s what you want: Can you

More information

Visual Basic 2008 Anne Boehm

Visual Basic 2008 Anne Boehm TRAINING & REFERENCE murach s Visual Basic 2008 Anne Boehm (Chapter 3) Thanks for downloading this chapter from Murach s Visual Basic 2008. We hope it will show you how easy it is to learn from any Murach

More information

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

Notes on Non-Chronologic Backtracking, Implication Graphs, and Learning Notes on Non-Chronologic Backtracking, Implication Graphs, and Learning Alan J. Hu for CpSc 5 Univ. of British Columbia 00 February 9 These are supplementary notes on these aspects of a modern DPLL-style

More information

Chapter 2.6: Testing and running a solution

Chapter 2.6: Testing and running a solution Chapter 2.6: Testing and running a solution 2.6 (a) Types of Programming Errors When programs are being written it is not surprising that mistakes are made, after all they are very complicated. There are

More information

(Refer Slide Time: 01.26)

(Refer Slide Time: 01.26) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture # 22 Why Sorting? Today we are going to be looking at sorting.

More information

Traditional Error Handling

Traditional Error Handling Exception Handling 1 Traditional Error Handling We have already covered several mechanisms for handling errors in C++. We ll quickly review them here. Returning Error Values One classic approach involves

More information

Stage 11 Array Practice With. Zip Code Encoding

Stage 11 Array Practice With. Zip Code Encoding A Review of Strings You should now be proficient at using strings, but, as usual, there are a few more details you should know. First, remember these facts about strings: Array Practice With Strings are

More information

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

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

3 Nonlocal Exit. Quiz Program Revisited

3 Nonlocal Exit. Quiz Program Revisited 3 Nonlocal Exit This chapter is about the commands catch and throw. These commands work together as a kind of super-stop command, which you can use to stop several levels of procedure invocation at once.

More information

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2 Python for Analytics Python Fundamentals RSI Chapters 1 and 2 Learning Objectives Theory: You should be able to explain... General programming terms like source code, interpreter, compiler, object code,

More information

After completing this appendix, you will be able to:

After completing this appendix, you will be able to: 1418835463_AppendixA.qxd 5/22/06 02:31 PM Page 879 A P P E N D I X A A DEBUGGING After completing this appendix, you will be able to: Describe the types of programming errors Trace statement execution

More information

(Refer Slide Time 6:48)

(Refer Slide Time 6:48) Digital Circuits and Systems Prof. S. Srinivasan Department of Electrical Engineering Indian Institute of Technology Madras Lecture - 8 Karnaugh Map Minimization using Maxterms We have been taking about

More information