Handling errors Exception handling and throwing Simple file processing.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Lecture 15: I/O and Parsing
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Handling errors Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts to be covered.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
11-Jun-15 Exceptions. 2 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.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
Lecture 7 File I/O (and a little bit about exceptions)‏
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 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.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Files and Streams CS 21a Chapter 11 of Horstmann.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Handling errors Writing robust code. 16/12/2004Lecture 10: Handling Errors2 Main concepts to be covered Defensive programming. –Anticipating that things.
CPSC150 Week 13 Chapter 12 Exceptions (from slides provided by textbook web site)
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Handling errors Main concepts to be covered Defensive programming. –Anticipating that things could go wrong. Exception handling and throwing. Error.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Chapter 20 – Streams and Binary Input/Output Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 12: Exception Handling
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
Two Ways to Store Data in a File Text format Binary format.
Lecture 4. Greenfoot 1 Pablo Romero, Department of Informatics Kinect in Greenfoot.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
Objects First With Java A Practical Introduction Using BlueJ Handling errors 1.0.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Chapter 11 Exceptions and Input/Output Operations.
OOP (Java): Exceptions/ OOP Objectives – –examine Java's exception handling Semester 2, Exceptions.
Handling errors Main concepts to be covered Defensive programming –Anticipating that things could go wrong Exception handling and throwing Error.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Handling errors Main concepts to be covered Defensive programming. –Anticipating that things could go wrong. Exception handling and throwing. Error.
Exceptions in the Java programming language J. W. Rider.
Introduction to Exceptions in Java
Exceptions The Need for Exceptions Throwing Exceptions
CSE 501N Fall ’09 17: Exception Handling
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
COS 260 DAY 27 Tony Gauvin.
COS 260 DAY 26 Tony Gauvin.
COS 260 DAY 26 Tony Gauvin.
Exception Handling.
Exceptions 25-Apr-19.
Tutorial Exceptions Handling.
Exceptions 22-Apr-19.
Exception Handling Contents
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Presentation transcript:

Handling errors Exception handling and throwing Simple file processing

Outline Error example Defensive Programming Throwing Exception Catching Exception Defining new Exception Types –Checked vs unchecked

Error situations Programmer errors –Incorrect implementation –Inappropriate object request Errors often arise from the environment: –incorrect URL entered –network interruption File processing is particularly error prone: –missing files –lack of appropriate permissions

Example: Runtime error Use: AddressBook friends = new AddressBook(); friends.removeDetails("frederik"); Result: java.lang.NullPointerException at AddressBook.removeDetails(AddressBook.java:119)... In class AddressBook: public void removeDetails(String key) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName());...} 1. returns null when key does not exist in book 2. trying to call method on null results in exception

Outline Error example Defensive Programming Throwing Exception Catching Exception Defining new Exception Types –Checked vs unchecked

Defensive programming Defensive programming in client-server interaction –server assumes that clients are not well behaved (and potentially hostile) –E.g. server checks arguments to constructors and methods Significant overhead in implementation

Defensive programming Modified method in class AddressBook: public void removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; } check argument

Server error reporting How to report illegal arguments? –To the user? is there a human user can they solve the problem? –To the client object return a diagnostic value throw an exception

Returning a diagnostic public boolean removeDetails(String key) { if(keyInUse(key)) { ContactDetails details = (ContactDetails) book.get(key); book.remove(details.getName()); book.remove(details.getPhone()); numberOfEntries--; return true; } else { return false; } did any errors arise?

QUIZ Which of the three remove methods use appropriate defensive programming? 1.none 2.A 3.B 4.C 5.A, B 6.A, C 7.B, C 8.All three private class Dictionary { List list = new ArrayList (); public void add(String w) { list.add(w); } public boolean removeA(String w) { list.remove(list.indexOf(w)); return true; } public boolean removeB(String w) { if (list.size()==0) return false; else return removeA(w); } public boolean removeC(String w) { if (!list.contains(w)) return false; else return removeA(w); }

Client responses Test the return value –Attempt recovery on error –avoid program failure Ignore the return value –cannot be prevented –likely to lead to program failure Exceptions are preferable

Outline Error example Defensive Programming Throwing Exception Catching Exception Defining new Exception Types –Checked vs unchecked

Exception-throwing principles A special language feature No special return value needed Errors cannot be ignored in the client –The normal flow-of-control is interrupted Specific recovery actions are encouraged

Throwing an Exception public ContactDetails getDetails(String key) { if (key==null) { throw new IllegalArgumentException( "null key in getDetails"); } return (ContactDetails) book.get(key); } An exception object is constructed: –new ExceptionType("..."); The exception object is thrown: –throw...

The effect of an exception The throwing method finishes prematurely No return value is returned Control does not return to the client's point of call –so the client cannot carry on regardless A client may 'catch' an exception

Outline Error example Defensive Programming Throwing Exception Catching Exception Defining new Exception Types –Checked vs unchecked

The try block Clients catching an exception must protect the call with a try block try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here }

The try block try { addressbook.saveToFile(filename); tryAgain = false; } catch(IOException e) { System.out.println("Unable to save to " + filename); tryAgain = true; } exception thrown from here control transfers to here

Catching multiple exceptions try {... ref.process();... } catch(EOFException e) { // Take action on an end-of-file exception.... } catch(FileNotFoundException e) { // Take action on a file-not-found exception.... }

The finally clause try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } finally { Perform any actions here common to whether or not an exception is thrown. }

The finally clause A finally clause is executed even if a return statement is executed in the try or catch clauses An uncaught or propagated exception still exits via the finally clause

QUIZ Which statement is executed immediately after the throw statement? 1.Line A 2.Line B 3.Line C 4.Line D 5.Program stops with exception failure 6.None of 1-5 public static void main(String[] args) { int arg = 0; double inv = inverse(arg); System.out.println(arg); } private static double inverse(int n) { double result=0; try { if (n==0) throw new IllegalArgumentException( "cannot take inverse of 0"); result = 1.0/n; } catch (IllegalArgumentException e) { e.printStackTrace(); } finally { return result; } A B C D

Outline Error example Defensive Programming Throwing Exception Catching Exception Defining new Exception Types –Checked vs unchecked

Defining new exceptions Extend Exception or RuntimeException Define new types to give better diagnostic information –include reporting and/recovery information

The exception class hierarchy

Exception categories Checked exception –subclass of Exception –use for anticipated failures –where recovery may be possible Unchecked exception –subclass of RuntimeException –use for unanticipated failures –where recovery is unlikely

Unchecked exceptions Use of these is 'unchecked' by the compiler Cause program termination if not caught –this is normal practice –NullPointerException is a typical example

Checked exceptions Checked exceptions are meant to be caught The compiler ensures that their use is tightly controlled –in both server and client Used properly, failures may be recoverable

The throws clause Methods throwing a checked exception must include a throws clause: public void saveToFile(String destinationFile) throws IOException {... }

Example: new checked exception public class NoMatchingDetailsException extends Exception { private String key; public NoMatchingDetailsException(String key) { this.key = key; } public String getKey() { return key; } public String toString() { return "No details matching '" + key + "' were found."; } }

QUIZ Any compiler errors ? 1.No compiler errors 2.Method A: needs ”throws” in header 3.Method A: needs ”try- catch” in body 4.Method B: needs ”throws” in header 5.Method main: needs ”throws” in header 6.Both 2 and 4 7.Both 4 and 5 8.Both 2, 4 and 5 9.Other errors public class Quiz3 { private static class MyException extends Exception {} private static void B() { throw new MyException(); } private static void A() { B(); } public static void main(String[] args) { try { A(); } catch (MyException e) { e.printStackTrace(); }

QUIZ What is the difference between checked and unchecked exceptions? 1.Unchecked exceptions may print any kind of message, whereas checked ones must print a programmer defined message 2.Unchecked exceptions must be handled with a programmed try/catch block, and checked exceptions with a try/catch/finally block 3.Unchecked exceptions need not be handled, but checked exceptions must be handled with a try/catch block 4.Checked exceptions must be handled with a programmed try/catch block, and unchecked exceptions with a try/catch/finally block 5.Checked exceptions need not be handled, but unchecked exceptions must be handled with a try/catch block 6.There is no formal difference between checked and unchecked exceptions

Outline Input/output Text files Terminal / keyboard Binary Files

Input-output Input-output is particularly error-prone –it involves interaction with the external environment java.io.IOException is a checked exception

Two ways to store data Text format –*.txt, *.java, *.xml –human-readable form –Sequence of characters integer stored as (ascii for "1" "2" "3" "4" "5“) –use Reader and Writer (and their subclasses) (based on char type) Binary format –*.doc, *.class, *.pdf –more compact and efficient integer stored as (12345 = 48*256+57) –Use InputStream and OutputStream (and their subclasses) (based on byte type)

Outline Input/output Text files Terminal / keyboard Binary Files

Text output Use the FileWriter class –open a file –write to the file –close the file Failure at any point results in an IOException.

Text output try { FileWriter writer = new FileWriter("name of file"); while(there is more text to write) {... writer.write(next piece of text);... } writer.close(); } catch(IOException e) { something went wrong with accessing the file }

QUIZ Which statements need to go in a try block? 1.A and B 2.B and C 3.C and D 4.D and E 5.A, B and C 6.B, C and D 7.C, D and E 8.A, B, C and D 9.B, C, D and E import java.io.*; public class Quiz4 { public static void main(String[] args) { String line = null; BufferedReader reader = null; reader = new BufferedReader( new FileReader("input.txt")); line = reader.readLine(); reader.close(); } E D C B A

Text input Use the FileReader class Augment with Scanner for line-based input try { Scanner in = new Scanner( new FileReader("name of file")); while(in.hasNextLine()) { String line = in.nextLine(); do something with line } in.close(); } catch(FileNotFoundException e) { the specified file could not be found } IOExceptions from FileReader “swallowed” by Scanner

Outline Input/output Text files Terminal / keyboard Binary Files

User input from terminal window Similar to reading from a text file –construct a Scanner from System.in –no closing needed Scanner in = new Scanner(System.in); System.out.println("type a line of input:"); String input = in.nextLine(); do something with input

QUIZ What is written if file ” input.txt ” does not exist? 1."IOException" 2."FileNotFoundException" 3."IOException”+”FileNotFoundException" 4.Something else is written 5.Compiler error: cannot have 2 catches 6.Compiler error: wrong order of catches 7.Other compiler error try { String line = null; BufferedReader reader = new BufferedReader( new FileReader("input.txt")); line = reader.readLine(); reader.close(); } catch (IOException e) { System.out.print ("IOException"); } catch (FileNotFoundException e) { System.out.print ("FileNotFoundException"); }

Outline Input/output Text files Terminal / keyboard Binary Files

Object streams ObjectOutputStream class can save entire objects to disk ObjectInputStream class can read objects back in from disk Objects are saved in binary format (and streams are used) similar to text files: –open, read/write, close

Writing object to file: BankAccount b1 =...; ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("accounts.dat")); out.writeObject(b1); Reading object from file: ObjectInputStream in = new ObjectInputStream(new FileInputStream("accounts.dat"); BankAccount b2 = (BankAccount) in.readObject(); Objects that are written to a file must be instances of a class implementing the Serializable interface: public class BankAccount implements Serializable {...} Serializable interface has no methods readObject may throw a (checked) ClassNotFoundException

Use container and write a single object Objects of any size written/read in a single statement: ArrayList a = new ArrayList();... // add many objects to array list out.writeObject(a) java.util.ArrayList implements Serializable Objects stored in the array list must also be instances of a class implementing Serializable