CMSC 202. Exceptions

Similar documents
Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Comp 249 Programming Methodology Chapter 9 Exception Handling

Exception Handling. 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:

Exceptions Handeling

Java Errors and Exceptions. Because Murphy s Law never fails

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

Exception Handling BASIC EXCEPTION HANDLING OBJECTIVES PREREQUISITES

Data Structures. 02 Exception Handling

Errors and Exceptions

COMP-202 Unit 9: Exceptions

Defensive Programming

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

Exceptions. What exceptional things might our programs run in to?

16-Dec-10. Consider the following method:

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

9. Java Errors and Exceptions

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

BBM 102 Introduction to Programming II Spring Exceptions

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

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

Java Exceptions Version June 2009

Chapter 4 Defining Classes I

Why Exceptions? (1.1) Exceptions. Why Exceptions? (1.2) Caller vs. Callee. EECS2030 B: Advanced Object Oriented Programming Fall 2018

Exceptions. EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG

COMP-202 Unit 9: Exceptions

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

ECE 122. Engineering Problem Solving with Java

Exception Handling. Chapter 8. Chapter 8 1

Chapter 14. Exception Handling and Event Handling ISBN

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

Encapsulation. Mason Vail Boise State University Computer Science

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2015 Lecture 11

Chapter 12 Exception Handling

6/4/12. Recursive void Methods. Chapter 11. Vertical Numbers. Vertical Numbers. Vertical Numbers. Algorithm for Vertical Numbers

CS64 Week 5 Lecture 1. Kyle Dewey

Intermediate Programming. Runtime Errors

COMP1008 Exceptions. Runtime Error

CS 3 Introduction to Software Engineering. 3: Exceptions

6. Java Errors and Exceptions

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Object Oriented Programming. Week 7 Part 1 Exceptions

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

An exception is simply an error. Instead of saying an error occurred, we say that an.

Quarter 1 Practice Exam

Chapter 8. Exception Handling

Video 2.1. Arvind Bhusnurmath. Property of Penn Engineering, Arvind Bhusnurmath. SD1x-2 1

6. Java Errors and Exceptions. Errors, runtime-exceptions, checked-exceptions, exception handling, special case: resources

Contents. I Introductory Examples. Topic 06 -Exception Handling

Designing Robust Classes

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Introduction to Computer Science II CS S-22 Exceptions

Written by John Bell for CS 342, Spring 2018

Java Program Coding Standards Programming for Information Technology

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Preconditions. CMSC 330: Organization of Programming Languages. Signaling Errors. Dealing with Errors

Traditional Error Handling

MSc/ICY Software Workshop Exception Handling, Assertions Scanner, Patterns File Input/Output

Chapter 4.!Data Abstraction: The Walls! 2011 Pearson Addison-Wesley. All rights reserved 4-1

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

Assertions, pre/postconditions

Exceptions. CS162: Introduction to Computer Science II. Exceptions. Exceptions. Exceptions. Exceptions. Exceptions

4. Java Project Design, Input Methods

BBM 102 Introduction to Programming II Spring 2017

CS159. Nathan Sprague

CH. 2 OBJECT-ORIENTED PROGRAMMING

Exceptions and Design

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

CS193j, Stanford Handout #25. Exceptions

Error Handling in C++

Data Abstraction: The Walls

Exceptions and Error Handling

Chapter 5. Exceptions. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

CS-152: Software Testing

Exceptions - Example. Exceptions - Example

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is 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

7. Java Input/Output. User Input/Console Output, File Input and Output (I/O)

Exceptions. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

G51PGP Programming Paradigms. Lecture OO-4 Aggregation

10/3/2018 Programming Data Structures. Casting: upcasting, downcasting Debugging again! Yay! Exception Handling

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

Array. Array Declaration:

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

CS/IT115 Lecture Alex Dusenbery Using Objects

Exceptions and Libraries

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

Transcription:

CMSC 202 Exceptions

Error Handling In the ideal world, all errors would occur when your code is compiled. That won t happen. Errors which occur when your code is running must be handled by some mechanism that allows the originator (detector) of the error to pass information to the recipient of the error who will know how to deal with the error. 11/2010 2

Procedural Error Handling In procedural languages, error handling was usually by convention. Programmers simply agreed on some standard way to report errors. Usually a function returned a value which had to be checked by the caller Not part of the language Completely unenforceable Programmers tended to ignore them Did you even know that C s printf() has a return value? Checking all return values would result in unreadable code 11/2010 3

Bank Account Deposit Example public static void main(string[] args){ BankAccount account = new BankAccount(100.00); Scanner input = new Scanner(System.in); // get amount to deposit System.out.println("Enter a Number: "); int amt = input.nextint(); if(amt > 0){ account.deposit(amt); else{ // reprompt the user? // exit the system? // user a default amount? 4

Bank Account Deposit Example In a banking application written in a procedural approach, we might write a function that verifies that the amount to deposit is acceptable. This function returns an int which must be interpreted by the calling code. public static final int BAD_AMOUNT = 1; public static final int OK_AMOUNT = -1; private static int verifyamount(double amount){ if(amount < 0){ return BAD_AMOUNT; return OK_AMOUNT; 11/2010 5

Errors By Convention In main, the code calls the function and checks the return value if(verifyamount(amt) == BankAccount.OK_AMOUNT){ account.deposit(amt); else{ // reprompt the user? // exit the sytem? // user a default amount? public void deposit(double amount){ this.balance += amount; 11/2010 6

Better Error Handling Separation of error detection from error handling Class implementer detects the error Class user decides what to do about the error Exit the program Output a message and continue the program Retry the function that had the error Ask the user what to do Many other possibilities Reduces complexity of code Code that works when nothing unusual happens is separated from the code that handles exceptional situations Enforced by language 11/2010 7

Exceptional What s an exceptional situation? As defined in the Sun Java tutorial: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. The program encounters a situation it doesn t know how to handle Different than a normal problem Program has enough information to know what to do next 11/2010 8

Exception Handling Removes error handling code from the code that caused the error Makes it possible to catch all kinds of errors, errors of a certain type, or errors of related types Is used in situations in which the system cannot recover. Is used when the error will be dealt with by a different part of the program (i.e., different scope) from that which detected the error Can be slow, but we don't care because errors occur very infrequently 11/2010 9

Introduction to Exception Handling Java library software (or programmer-defined code) provides a mechanism that signals when something unusual happens This is called throwing an exception In another place in the program, the programmer must provide code that deals with the exceptional case This is called handling the exception Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 10

try-throw-catch The basic way of handling exceptions in Java consists of the try-throw-catch trio 11/2010 11

try-throw-catch example public void deposit(double amount){ try{ if(amount < 0) throw new Exception("Deposit Negative Amount"); this.balance += amount; catch(exception e){ // do something about the exception This example is essentially a if-else expression, but to see the true separation of error detection from error handling we should look at how the try-throw-catch mechanism works. 11/2010 12

The try block Code which calls a method that might throw an exception is placed inside a try block The try block contains the code for the basic algorithm It tells what to do when everything goes smoothly It is called a try block because it "tries" to execute the case where all goes as planned Code which handles the exception is placed into a catch block Catch block immediately follows the try block 11/2010 13

Better Bank Account Deposit Code public static void main(string[] args){ BankAccount account = new BankAccount(100.00); try{ Scanner input = new Scanner(System.in); // get amount to deposit System.out.println("Enter a Number: "); double amt = input.nextdouble(); account.deposit(amt); catch(exception e){ // do something with the exception 11/2010 14

try-throw-catch Mechanism When an exception is thrown, the execution of the surrounding try block is stopped Normally, the flow of control is transferred to another portion of code known as the catch block The value thrown is the argument to the throw operator, and is always an object of some exception class The execution of a throw statement is called throwing an exception Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 15

try-throw-catch Mechanism When an exception is thrown, the catch block begins execution The catch block has one parameter The exception object thrown is plugged in for the catch block parameter The execution of the catch block is called catching the exception, or handling the exception Whenever an exception is thrown, it should ultimately be handled (or caught) by some catch block Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 16

try-throw-catch Mechanism catch( Exception e ) {... n n The identifier e in the above catch block heading is called the catch block parameter The catch block parameter does two things: 1. It specifies the type of thrown exception object that the catch block can catch (e.g., an Exception class object above) 2. It provides a name (for the thrown object that is caught) on which it can operate in the catch block Note: The identifier e is often used by convention, but any nonkeyword identifier can be used Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 17

try-throw-catch Mechanism When a try block is executed, two things can happen: 1. No exception is thrown in the try block The code in the try block is executed to the end of the block The catch block(s) is (are) skipped The execution continues with the code placed after the catch block(s) Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 18

try-catch Control Flow try { // code that might throw an Exception // more code catch(exception e) { // handle error here Case 1 The try block does NOT throw an Exception. When the try block completes, the catch block is skipped // Method continues here 11/2010 19

try-throw-catch Mechanism 2. An exception is thrown in the try block and caught in the catch block The rest of the code in the try block is skipped Control is transferred to a following catch block (in simple cases) The thrown object is plugged in for the catch block parameter The code in the catch block is executed The code that follows that catch block is executed (if any) Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 20

try-catch Control Flow try { throw new Exception( message ); // more code catch(exception e) { // handle error here Case 2 The try block throws an Exception. The try block terminates, the catch block executes, code following the catch block executes // Method continues here 11/2010 21

Exception Classes The Java language defines a basic Exception class There are more exception classes in the standard Java libraries New exception classes can be defined like any other class All predefined exception classes have the following properties: There is a constructor that takes a single argument of type String The class has an accessor method getmessage that can recover the string given as an argument to the constructor when the exception object was created All programmer-defined classes should have the same properties Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 22

Exception Classes from Standard Packages The predefined exception class Exception is the root class for all exceptions Every exception class is a descendent class of the class Exception Although the Exception class can be used directly in a class or program, it is most often used to define a derived class The class Exception is in the java.lang package, and so requires no import statement Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 23

Using the getmessage Method... // method code try {... throw new Exception( StringArgument );... catch(exception e) { String message = e.getmessage(); System.out.println(message); System.exit(0);... Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 24

Using the getmessage Method Every exception has a String instance variable that contains some message This string typically identifies the reason for the exception In the previous example, StringArgument is an argument to the Exception constructor This is the string used for the value of the string instance variable of exception e Therefore, the method call e.getmessage() returns this string Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 25

Where does it start? Regular modular programming will cause the call stack to grow. Each frame of the stack will execute a series of statements that will eventually lead to the program to terminate successfully. Any time an Exception is generated the series of operations that would normally occur in sequential ordering is halted at that statement. Baz() Called from Bar() Generates the exception Bar() Called from Foo() Foo() Called from Main() main()

Why does my program crash? The exception will be generated in a method. Throw will throw the Exception Object down the stack to a catch block. When no catch block is present in the previous stack frame, it thrown down until it is caught. If nothing catches that exception, your program will crash. Method where error occurred Method without a catch statement Method without a catch statement main() without a catch statement?????

Why does my program crash? If every method up to and including the main method simply includes a throw an exception, that exception may be thrown but never caught In a GUI program (i.e., a program with a windowing interface), nothing happens - but the user may be left in an unexplained situation, and the program may be no longer be reliable In non-gui programs, this causes the program to terminate with an error message giving the name of the exception class Every well-written program should eventually catch every exception by a catch block in some method Copyright 2008 Pearson Addison- Wesley. 11/2010 All rights reserved 28