Exceptions. Your computer takes exception. The Exception Class. Causes of Exceptions

Similar documents
10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

CS 11 C track: lecture 1

Workflow model GM AR. Gumpy. Dynagump. At a very high level, this is what gump does. We ll be looking at each of the items described here seperately.

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

CMPT 125 Assignment 2 Solutions

Threads and Concurrency in Java: Part 1

Threads and Concurrency in Java: Part 1

Python Programming: An Introduction to Computer Science

n Maurice Wilkes, 1949 n Organize software to minimize errors. n Eliminate most of the errors we made anyway.

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

Lecture 9: Exam I Review

Java net programming II

One advantage that SONAR has over any other music-sequencing product I ve worked

Threads and Concurrency in Java: Part 2

Abstract Data Types (ADTs) Stacks. The Stack ADT ( 4.2) Stack Interface in Java

Definitions. Error. A wrong decision made during software development

MR-2010I %MktBSize Macro 989. %MktBSize Macro

How do we evaluate algorithms?

Exercise Set: Implementing an Object-Oriented Design

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CMSC Computer Architecture Lecture 12: Virtual Memory. Prof. Yanjing Li University of Chicago

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

CS 111: Program Design I Lecture 16: Module Review, Encodings, Lists

CS 111: Program Design I Lecture # 7: First Loop, Web Crawler, Functions

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Introduction to Sigma Notation

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Hash Tables. Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015.

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

The isoperimetric problem on the hypercube

CSC165H1 Worksheet: Tutorial 8 Algorithm analysis (SOLUTIONS)

High-Grade Testing Using JUnit

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

Java Inheritance. Class ADT (Abstract Data Type) Interface. Classes implement the concept of ADT: Interfaces define interaction contracts: Rui Moreira

condition w i B i S maximum u i

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

K-NET bus. When several turrets are connected to the K-Bus, the structure of the system is as showns

Overview. Another application of Interfaces: the Strategy Design Pattern. n Java interfaces

CS 111: Program Design I Lecture 19: Networks, the Web, and getting text from the Web in Python

ifs considered Harmful

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Guide to Applying Online

Oracle Server. What s New in this Release? Release Notes

Chapter 4 The Datapath

Computers and Scientific Thinking

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

3.1 Overview of MySQL Programs. These programs are discussed further in Chapter 4, Database Administration. Client programs that access the server:

CS 111: Program Design I Lecture # 7: Web Crawler, Functions; Open Access

Weston Anniversary Fund

Python Programming: An Introduction to Computer Science

Morgan Kaufmann Publishers 26 February, COMPUTER ORGANIZATION AND DESIGN The Hardware/Software Interface. Chapter 5.

Using VTR Emulation on Avid Systems

top() Applications of Stacks

Module 8-7: Pascal s Triangle and the Binomial Theorem

CS 111: Program Design I Lecture 5: US Law when others have encryption keys; if, for

Parabolic Path to a Best Best-Fit Line:

GE FUNDAMENTALS OF COMPUTING AND PROGRAMMING UNIT III

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Location Steps and Paths

JCF: case studies. Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf.

Baan Tools User Management

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

CS 111: Program Design I Lecture #26: Heat maps, Nothing, Predictive Policing

Lecturers: Sanjam Garg and Prasad Raghavendra Feb 21, Midterm 1 Solutions

Our Learning Problem, Again

Chapter 1. Introduction to Computers and C++ Programming. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Lecture 7 7 Refraction and Snell s Law Reading Assignment: Read Kipnis Chapter 4 Refraction of Light, Section III, IV

WORKED EXAMPLE 7.1. Producing a Mass Mailing. We want to automate the process of producing mass mailings. A typical letter might look as follows:

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

27 Refraction, Dispersion, Internal Reflection

CSE 111 Bio: Program Design I Lecture 17: software development, list methods

CSE 111 Bio: Program Design I Class 11: loops

Computer Science Foundation Exam. August 12, Computer Science. Section 1A. No Calculators! KEY. Solutions and Grading Criteria.

CSE 417: Algorithms and Computational Complexity

Creating Test Harnesses and Starter Applications

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

. Written in factored form it is easy to see that the roots are 2, 2, i,

Code Review Defects. Authors: Mika V. Mäntylä and Casper Lassenius Original version: 4 Sep, 2007 Made available online: 24 April, 2013

CS 111 Green: Program Design I Lecture 27: Speed (cont.); parting thoughts

CS 111: Program Design I Lecture 20: Web crawling, HTML, Copyright

Using the Keyboard. Using the Wireless Keyboard. > Using the Keyboard

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

Algorithm. Counting Sort Analysis of Algorithms

Lecture 1: Introduction and Strassen s Algorithm

ENGI 4421 Probability and Statistics Faculty of Engineering and Applied Science Problem Set 1 Descriptive Statistics

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CS 111: Program Design I Lecture 18: Web and getting text from it

ENGR Spring Exam 1

The number n of subintervals times the length h of subintervals gives length of interval (b-a).

Java Expressions & Flow Control

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

fgrep - Linux Command

Transcription:

Your computer takes exceptio s s are errors i the logic of a program (ru-time errors). Examples: i thread mai java.io.filenotfoud: studet.txt (The system caot fid the file specified.) i thread mai java.lag.nullpoiter: at FileProcessor.mai(FileProcessor.java:9) 1 Questio: do all ru-time errors cause s? Causes of s The Class Most exceptios happe because of corer cases : your program does somethig at the boudaries of what Java kows how to hadle. For example: Java kows how to ope files for readig, mostly. But if you tell it to ope a file that does t exist, it does t kow how it should behave. It throws a exceptio, ad gives the programmer a opportuity to defie how the program should react. As with aythig i Java, is a class Method void pritstacktrace() Strig getlocalizedmessage() Strig tostrig() What it does Prits the seuece of method calls leadig up to the statemet that caused the. Returs a detail message. Returs the class ame ad detail message. The methods i the class ca be useful for debuggig, as we will see.

The class hierarchy (partial) Pitch ad catch Error Throwable Whe a Java statemet causes a (called throwig the ), by default Java abruptly eds the program. IO ClassNotFoud Rutime To stop this default behavior, you ca write code that catches the throw. EOF FileNotFoud UkowHost Arithmetic ClassCast IdexOut OfBouds NullPoiter Catch: A example // For Scaer class public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); while(iput.hasnextlie()) System.out.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the file 'studet.txt'."); try/catch sytax try <statemets that might cause a exceptio>; catch block is a exceptio hadler for oe type of exceptio. catch(<type1> e1) <statemets> catch(<typen> en) <statemets> try block idicates that the eclosed statemets have exceptio hadlers associated with them. The type of exceptio that the catch block hadles is idicated with a parameter. You ca have as may catch blocks for oe try block as you like. They must each hadle a differet type of exceptio.

Cotrol Flow with try/catch Catch: A example try <statemets that might cause a exceptio>; catch(<type1> e1) <statemets> catch(<typen> en) <statemets> <statemets after try/catch> If o exceptio occurs durig the try block: jump to statemets after all the catch blocks. If a exceptio occurs i the try block: jump to the first hadler for that type of exceptio. After the catch fiishes, jump to the statemet after all the catch blocks. // For Scaer class public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); while(iput.hasnextlie()) System.out.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the file 'studet.txt'."); fially Remember try <statemets that might cause a exceptio>; catch(<type1> e1) <statemets> catch(<typen> en) <statemets> fially <statemets i here are doe whether a exceptio occurred or ot> Whe a exceptio occurs you jump to the appropriate catch block you do ot ever jump back to the try block If you absolutely must complete the try block you eed to put it iside a loop

Example Strig fileame = ull; Scaer ifromfile = ull; try Scaer ifromkbd = ew Scaer(System.i); System.out.prit("Eter file ame> "); fileame = ifromkbd.extlie(); ifromfile = ew Scaer(ew File(fileame)); catch (FileNotFoud e) System.out.pritl("Error opeig file " + fileame); /* but the file might ot be ope */ Example Strig fileame = ull; Scaer ifromfile = ull; boolea successfulope=false; do try Scaer ifromkbd = ew Scaer(System.i); System.out.prit("Eter file ame> "); fileame = ifromkbd.extlie(); ifromfile = ew Scaer(ew File(fileame)); successfulope=true; catch (FileNotFoud e) System.out.pritl("Error opeig file " + fileame); while (!successfulope); /* if we get this far, the file is ope */ Stack Traces Displayig the stack trace ifo How do you kow what wet wrog? All exceptios have methods that retur iformatio about the cause of the : Method getlocalizedmessage() getstacktrace() pritstacktrace() Descriptio Returs a Strig cotaiig a descriptio of the error Returs a array of StackTraceElemet objects, each of which cotais ifo about where the error occurred Displays the Stack Trace o the cosole. // For Scaer class public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); while(iput.hasnextlie()) System.out.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the file 'studet.txt'."); System.out.pritl(exceptio.getLocalizedMessage()); exceptio.pritstacktrace();

Multiple catch blocks Multiple catch blocks // For Scaer class // For Scaer class public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); PritWriter pw = ew PritWriter(ew File( uoted.txt )); public static void mai(strig [] args) try File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); PritWriter pw = ew PritWriter(ew File( uoted.txt )); while(iput.hasnextlie()) pw.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the file 'studet.txt'."); catch(io exceptio) System.out.pritl( Could ot write to file uoted.txt. ); while(iput.hasnextlie()) pw.pritl("> " + iput.extlie()); catch(filenotfoud exceptio) System.out.pritl("Could ot fid the iput file."); System.out.pritl(exceptio.getLocalizedMessage()); exceptio.pritstacktrace(); catch(io exceptio) System.out.pritl( Could ot write to file uoted.txt. ); Checked ad Uchecked s Checked ad Uchecked s s happe while the program is ruig For most kids of s, the compiler is happy to let the programmer make mistakes that could lead to a exceptio at rutime. Uchecked (by the compiler) s They are caused by programmer error. The compiler lets the programmer screw up. e.g., NullPoiter, IdexOutOfBouds s happe while the program is ruig For most kids of s, the compiler is happy to let the programmer make mistakes that could lead to a exceptio at rutime. But, for certai kids of exceptios, the compiler will check to see if your code might cause a exceptio at ru-time. Checked (by the compiler) s: They are caused by thigs outside of the programmer s cotrol (eg, a file does t exist). The compiler reuires that the programmer declare what to do if the occurs.

Checked ad Uchecked s Optios for Checked s Error Throwable If the compiler detects that a statemet might cause a Checked, it reuires the programmer to do either of the followig: IO ClassNotFoud Rutime 1. Catch the EOF FileNotFoud UkowHost Arithmetic ClassCast 2. Declare that crashig is acceptable Use the throws clause i the method sigature IdexOut OfBouds NullPoiter Otherwise, the program will ot compile. Throws: A example Catch or throw? // For Scaer class public static void mai(strig [] args) throws FileNotFoud File iputfile = ew File("studet.txt"); Scaer iput = ew Scaer(iputFile); while(iput.hasnextlie()) System.out.pritl("> " + iput.extlie()); Whe should you catch a exceptio, ad whe should you declare that it ca be throw? Usually, if your catch block is ot goig to do aythig besides prit a error message ad uit the program, it s better to just throw the exceptio You should oly catch a exceptio if you re really goig to hadle the error so that it wo t affect the rest of the program.

Causig a ruckus Guess what you ca create your very ow s, ay time you wat! The throw keyword: (ote: NOT the same as the throws keyword!) Use it to make your code throw a exceptio throw ew (); Maily useful for passig messages betwee methods that are t easily doe with returs