Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

Similar documents
Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

ECE 122. Engineering Problem Solving with Java

11/1/2011. Chapter Goals

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

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

Exceptions - Example. Exceptions - Example

Intro to Computer Science II. Exceptions

Errors and Exceptions

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSCI 261 Computer Science II

BBM 102 Introduction to Programming II Spring Exceptions

Fundamentos de programação

Exceptions. CSC207 Winter 2017

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

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

CS159. Nathan Sprague

COMP-202 Unit 9: Exceptions

Input-Output and Exception Handling

Exception-Handling Overview

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

Chapter 13 Exception Handling

BBM 102 Introduction to Programming II Spring 2017

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

Object Oriented Programming. Week 7 Part 1 Exceptions

Lecture 19 Programming Exceptions CSE11 Fall 2013

Fundamentals of Object Oriented Programming

COMP-202 Unit 9: Exceptions

Programming II (CS300)

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

Java Errors and Exceptions. Because Murphy s Law never fails

More on Exception Handling

More on Exception Handling

Exceptions Handling Errors using Exceptions

Administrivia. CPSC Winter 2008 Term 1. Department of Computer Science Undergraduate Events

Chapter 12 Exception Handling

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

ITI Introduction to Computing II

Programming II (CS300)

ITI Introduction to Computing II

EXCEPTION HANDLING. Summer 2018

Java Exception. Wang Yang

Exception Handling. Exception Handling

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

CS 3 Introduction to Software Engineering. 3: Exceptions

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

EXCEPTIONS. Fundamentals of Computer Science I

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

C16b: Exception Handling

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

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

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Introduction to Computer Science II CS S-22 Exceptions

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

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

Correctness and Robustness

CS 2230 CS II: Data structures. Meeting 20: generic types, exceptions, higher order functions Brandon Myers University of Iowa

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

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

Internal Classes and Exceptions

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

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Object-Oriented Programming Design Topic : Exception Programming

CS159. Nathan Sprague

Programming Languages and Techniques (CIS120)

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO

Chapter 11: Exceptions and Advanced File I/O

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

Exceptions and Error Handling

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

Exceptions and Libraries

Motivations. Chapter 12 Exceptions and File Input/Output

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

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

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Exceptions. James Brucker

CS Programming I: Exceptions

Abstract Classes, Exceptions

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

EXCEPTIONS. Java Programming

Excep&ons and file I/O

Exception Handling Generics. Amit Gupta

What are Exceptions?

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Projeto de Software / Programação 3 Tratamento de Exceções. Baldoino Fonseca/Márcio Ribeiro

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

CS 455 Midterm Exam 2 Fall 2015 [Bono] Nov. 10, 2015

COMP1008 Exceptions. Runtime Error

Data Structures. 02 Exception Handling

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

Transcription:

Exception Handling General idea Checked vs. unchecked exceptions Semantics of throws try-catch Example from text: DataAnalyzer Exceptions [Bono] 1

Announcements Lab this week is based on the textbook example we ll discuss today. This Thurs. (10/19) lecture is pre-taped. You can watch it from home. Claire s office hours cancelled Thurs. 10/19 Exceptions [Bono] 2

Lecture references Big Java Core Java, Volume I, 8 th Ed, by Horstmann and Cornell, Prentice Hall, 2008 Exceptions [Bono] 3

Errors and recovery options Suppose an error occurs while our program is running. Good program responses: Report the error and return to safe state and allow user execute other commands or allow user to save all work and and terminate program gracefully [From Core Java] Not so good program responses: program crashes program is mum about the error Exceptions [Bono] 4

Exceptions idea Allows us to separate point of error detection from point of error recovery First, an example to refer to in our discussions Exceptions [Bono] 5

Textbook example Code is in Section 11.5 Problem: read in a bunch of data from a file with a specific format and process the data (computes the sum) Example file in1 (first line is number of values): 3 1.45-2.1 0.05 Exceptions [Bono] 6

Why exceptions? I Recall: Exceptions allow us to separate point of error detection from point of error recovery Why? cleaner code for normal case. E.g.: for (int i = 0; i< numvals; i++) { readvalue(in, i); Exceptions [Bono] 7

Why exceptions? II May not have enough info in method where error is detected Ex: suppose if we get a bad data value in readvalue, we want to ask for a new file name. But the code that gets file name is in main Call stack: main calls error can be handled here readfile calls readdata calls readvalue calls in.nextdouble() ERROR detected here Exceptions [Bono] 8

Why exceptions? III All that catch-throw stuff looks confusing Is there some alternative? returning an error code from our function but in Java we can only return one value. use return value for the normal value, throw an exception for one or more abnormal situations Exceptions [Bono] 9

Why exceptions? IV Some Java library methods throw exceptions, So, even if we don't want to use exceptions we need to know a little bit about the mechanism to even compile any of our code that uses those parts. Our first such example: trying to open a file that isn't there. Exceptions [Bono] 10

Classification of Java Exceptions Throwable checked exceptions shown darker Error Exception RunTime Exception IOException CloneNot Supported Exception NullPointer Exception Number Format Exception FileNotFound Exception Exceptions [Bono] 11

Unchecked Exceptions Unchecked: Error, RunTimeException RunTimeException: Don't throw, don't catch: Fix the bug in your program! e.g., ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException Error: Not your fault; internal error you can't recover from e.g., ran out of heap memory Exceptions [Bono] 12

Checked Exceptions Checked: all other Exception subclasses These are largely user errors that you may handle with the exception mechanism. e.g., EOFException, FileNotFoundException, These are the ones that your code has to do something about (Why IV earlier) Exceptions [Bono] 13

Unchecked IO-related exceptions Major category of checked exceptions: IOException However, next() and nextint() can throw unchecked exceptions (InputMismatchException and NoSuchElementException) Can handle issue without using exception handling. Exceptions [Bono] 14

Java exception handling mechanism throw / throws: someone else will deal with the exception try - catch: my code will deal with the exception try-with-resources: automatically closes a file upon completion whether an exception happened or not Exceptions [Bono] 15

Java method throws an exception. What do I do? Easiest response: we throw the exception onwards. Ex: (Total.java, Sect.11.1) public static void main(string[] args) throws FileNotFoundException { File inputfile = new File(inputFileName); Scanner in = new Scanner(inputFile); //... code to read the file if file not found: main exits immediately; program crashes Exceptions [Bono] 16

(Not in main) Java method throws an exception. What do I do? (cont.) Easiest response: we throw the exception to our caller. If you're not main, and you don't know how to handle exception, perfectly ok to throw it to caller: public int[] read(string filename) throws FileNotFoundException { File inputfile = new File(fileName); Scanner in = new Scanner(inputFile); file not found: control returns to caller immediately. caller has to catch or throw Exceptions [Bono] 17

Catching Exceptions To catch an exception have to put the code that may throw the exception in a try block of a try-catch statement. the part that handles the exception is in the catch block try { // some code that may throw an exc. catch (ExceptionType e) { // some code that handles the exception // (e.g., reports the error and recovers, // or reports and exits) Exceptions [Bono] 18

Ex: Try-catch flow-of-control Normal flow of control (no exc. thrown) try { File infile = new File(fileName); Scanner in = new Scanner(inFile); String input = in.next(); int value = Integer.parseInt(input); catch (FileNotFoundException e) { System.out.println("File not found."); catch (NumberFormatException exception) { System.out.println("Input was not a number."); Exceptions [Bono] 19

Ex: Try-catch flow-of-control File not found exception try { File infile = new File(fileName); Scanner in = new Scanner(inFile); String input = in.next(); int value = Integer.parseInt(input); catch (FileNotFoundException e) { System.out.println("File not found."); catch (NumberFormatException exception) { System.out.println("Input was not a number."); Exceptions [Bono] 20

Ex: Try-catch flow-of-control NumberFormatException thrown by parseint try { File infile = new File(fileName); Scanner in = new Scanner(inFile); String input = in.next(); int value = Integer.parseInt(input); catch (FileNotFoundException e) { System.out.println("File not found."); catch (NumberFormatException exception) { System.out.println("Input was not a number."); Exceptions [Bono] 21

Ex: Try-catch flow-of-control public void somemethod( ) { don t need throws in header because try { unchecked exception File infile = new File(fileName); Scanner in = new Scanner(inFile); String input = in.next(); int value = Integer.parseInt(input); catch (FileNotFoundException e) { NumberFormatException thrown by parseint; no handler for it System.out.println("File not found."); exits method immediately Exceptions [Bono] 22

Ex: What if exception matches multiple catch clauses FileNotFoundException is a subclass of IOException; FileNotFound thrown by Scanner try { File infile = new File(fileName); Scanner in = new Scanner(inFile); String input = in.next(); int value = Integer.parseInt(input); matches most specific Exc. type catch (FileNotFoundException e) { System.out.println("File not found."); catch (IOException exception) { exception.printstacktrace(); only one catch clause executed Exceptions [Bono] 23

What about recovery? So far have only seen printing a message. Recovery is in the context of a larger program We'll do a larger example presently. But first Exceptions [Bono] 24

Do not squelch exceptions! Suppose my code can throw a checked exception: File infile = new File(fileName); Scanner in = new Scanner(inFile); Bummer, it won't compile. this will shut it up! try { File infile = new File(fileName); Scanner in = new Scanner(inFile); catch (FileNotFoundException e) { Don't do this! Means that instead of handling the error, when that error comes up the behavior is undefined. Exceptions [Bono] 25

Case Study Code is in Section 11.5 Handling Input Errors Problem: read in a bunch of data from a file with a specific format and process the data (computes the sum) Example file in1 (first line is number of values): 3 1.45-2.1 0.05 Exceptions [Bono] 26