File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.

Slides:



Advertisements
Similar presentations
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Advertisements

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
CS102--Object Oriented Programming
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
1 Chapter 10: Exceptions and I/O Streams Original Slides by John Lewis and William Loftus Modified significantly by Bob Roggio.
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.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
© 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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
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.
Files and Streams CS 21a Chapter 11 of Horstmann.
Chapter 8: Exceptions and I/O Streams Copyright 2002, Matthew Evett. These slides are based on slides copyrighted by John Lewis and William Loftus, 2002,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Outline Polymorphic References Polymorphism via Inheritance Polymorphism via Interfaces Sorting.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
10-1 Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled.
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Exceptions Chapter 10 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Pengantar OOP Class-Java. 2 Software Development Tools Using Sun Java SDK alone Source File(s) (.java) Programmer Compiler (javac) Class File(s) (.class)
Chapter 10 Exceptions 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
© 2004 Pearson Addison-Wesley. All rights reserved December 5, 2007 I/O Exceptions & Working with Files ComS 207: Programming I (in Java) Iowa State University,
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
CSE 1201 Object Oriented Programming
File I/O CLI: File Input CLI: File Output GUI: File Chooser
10 Exceptions Software Solutions Lewis & Loftus java 5TH EDITION
Introduction to Exceptions in Java
Introduction to Exceptions in Java
04/14/14 Exceptions.
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
Abdulmotaleb El Saddik University of Ottawa
Web Design & Development Lecture 7
Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
I/O Exceptions & Working with Files
Chapter 11 Exceptions Java Software Solutions
Presentation transcript:

File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause Reading for this lecture: L&L 10.8, 11.1 – 11.6

2 CLI File Input In a CLI, we want the user to select a file within a directory system so that its contents can be read and processed However, we must rely on the user typing in the file name (including any required path name) We can get the file name via a Scanner on System.in using the nextLine method We can read the file data via a Scanner on a File object using the nextLine method again

3 CLI File Input: Example import java.util.Scanner; import java.io.*; public class FileDisplay { public static void main (String [] args) throws IOException { Scanner scan = new Scanner(System.in); System.out.println("Enter name of file to display"); File file = new File(scan.nextLine()); scan = new Scanner (file); // done with keyboard while (scan.hasNext()) // ctl-D returns false System.out.println(scan.nextLine()); }

4 CLI File Output In a CLI, we want the user to create a file within a directory system so that its contents can be written (or overwritten!) Be careful: Your code should check for a file by that name and ask user if OK to overwrite it. Again, we rely on the user typing in the file name Again, we can get the file name via a Scanner on System.in using the nextLine method We can write the file data via a PrintStream on a File object using the println method ( System.out is a PrintStream object)

5 CLI File Output: Example import java.util.Scanner; import java.io.*; public class FileWrite { public static void main (String [] args) throws IOException { // Get filename and instantiate File object as before PrintStream out = new PrintStream(file); // Use ctl-D to close System.in // so scan.hasNext() will return false while (scan.hasNext()) { String line = scan.nextLine(); out.println(line); } out.close(); }

6 GUI File I/O In a GUI, requiring the user to enter a file name (including a path name or not) is considered to be NOT very user friendly We want our program to offer a choice of the available files so that the user can: –Move around within the available directories –Select one of the files shown in a directory

7 File Chooser in GUI’s Recall that a dialog box is a small window that "pops up" to interact with the user for a brief, specific purpose A file chooser, the JFileChooser class, supports a simple dialog box for this process See DisplayFile.java (page 521) DisplayFile.java

8 Example: DisplayFile code segment JFileChooser chooser = new JFileChooser(); int status = chooser.showOpenDialog(frame); // There is also a showSaveDialog(frame) if (status != JFileChooser.APPROVE_OPTION) ta.setText ("No File Chosen"); else { // read file File file = chooser.getSelectedFile(); Scanner scan = new Scanner (file);...

9 File Input/Output Notice that the main method in all three of these examples indicates that the code may throw an IOException If an error such as “file not found” occurs during a file operation, an IOException is generated by the system We’ll study exceptions in the next lecture

10 Exceptions An exception is an object that flags/ describes the occurrence of an unusual or erroneous situation Java has a predefined set of Exception classes for errors that can occur during execution –e.g ArithmeticException We can write our own Exception classes if needed When code in a program detects an “impossible condition”, it can throw a defined exception object The manner in which exceptions are processed is an important design consideration

Throwing Exceptions For code to “throw” an exception: –It must detect the “impossible” situation –Instantiate and “throw” an exception object Example (throw is a Java reserved word): if (boolean logic to detect impossible situation) throw new NameOfException(“text to print”); Some Java statements or methods in the class library may throw exceptions this way

12 Handling Exceptions A program can deal with an exception in one of three ways: –ignore it (Let the JVM shut down the program) –handle it where it occurs –handle it at another place in the program If we ignore it, we get something like this in the interactions pane (See Zero.java): java.lang.ArithmeticException: / by zero at Zero.main(Zero.java:17) at sun.reflect.NativeMethodAccessor… …

13 The try Statement / catch Clause To handle an exception in a program, the line that may throw the exception is executed within a try statement followed by one or more catch clauses Each catch clause has an exception type and reference name and is called an exception handler If an exception occurs, –Processing stops in the body of the try statement –Processing continues at the start of the first catch clause matching the type of exception that occurred The reference name can be used in the catch clause to get information about the exception

14 The finally Clause A try statement can have an optional clause following the catch clauses, designated by the reserved word finally The Java statements in the finally clause are always executed –If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete –If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete

Example of try-catch-finally try { System.out.println(Integer.parseInt(string)); } catch (NumberFormatException e) { System.out.println(“Caught exception: ” + e); } finally { System.out.println(“Done.”); }

16 Exception Propagation An exception can be propagated up to the caller to be handled at a higher level if it is not appropriate to handle it where it occurs Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method and/or JVM See Propagation.java (page 546) Propagation.java See ExceptionScope.java (page 547) ExceptionScope.java

17 Checked/Unchecked Exceptions An exception is considered to be either checked or unchecked A RunTimeException or its decendents such as ArithmeticException, NullPointerException, etc are the only ones considered to be unchecked All other exceptions are considered to be checked Many of the checked exceptions are related to input / output, e.g. IOException

Checked Exceptions If a method can generate a checked exception, it must have a throws clause in its header (Note: “ throws ” is a different reserved word) If method1 calls method2 that has a throws clause in its method header, method1 must: –Use try-catch around the call to method2 OR –Have a throws clause in its own method header The compiler will issue an error if a checked exception is not caught or listed in a throws clause

Example of the throws clause public class FileDisplay { public FileDisplay() throws IOException { Scanner scan = new Scanner(System.in); System.out.println("Enter name of file"); File file = new File(scan.nextLine()); // this line may throw an IOException // and its not inside a try statement scan = new Scanner (file);

Unchecked Exceptions An unchecked exception does not require explicit handling Code or calls to a method that may generate an unchecked exception can be put inside a try-catch statement, but that is optional