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.

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

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.
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.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
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.
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. 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.
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,
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
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.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
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.
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.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
© 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,
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Introduction to Exceptions in Java
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
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
Exceptions 25-Apr-19.
Tutorial Exceptions Handling.
Exceptions 22-Apr-19.
Exception Handling Contents
I/O Exceptions & Working with Files
Exceptions 10-May-19.
Chapter 11 Exceptions Java Software Solutions
Java Basics Exception Handling.
Exceptions 5-Jul-19.
CMSC 202 Exceptions.
Basic Exception Handling
Presentation transcript:

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

Input and Output There are three predefined standard streams: e.g System.out.println writes to the console 2 Stream System.in System.out System.err Purpose reading input writing output writing errors Default Device Keyboard Monitor monitor

Reading in using the Scanner class The code below creates an object of the Scanner class. What is returned is an Iterator that allows you read in from the keyboard – the Scanner class implements the iterator interface. Scanner scan = new Scanner(System.in) – reads from the keyboard Scanner scan = new Scanner(filename) – reads in from an input file 3

I/O Streams A stream is a sequence of bytes that flows from a source to a destination In a program, we read information from an input stream and write information to an output stream 4

STREAMS of DATA multiple streams A program can manage multiple streams at a time The java.io package contains many classes to read from: a file, the keyboard, the console etc. 5

I/O Stream Categories The classes in the I/O package divide input and output streams into other categories An I/O stream is either a: character stream, which deals with text data Or A byte stream, which deal with byte data(1 & 0’s) 6

I/O Streams An I/O stream is also either a data stream, which acts as either a source or destination (keyboard or file) processing stream, which alters or manages information in the data stream - this stream will take characters and assemble them into words 7

IO streams to and from the Console There are three standard I/O streams to and from the console: standard output – defined by System.out standard input – defined by System.in standard error – defined by System.err We use System.out when we execute System.out.println statements 8

Types of input standard input – defined by System.in standard output – defined by System.out standard error – defined by System.err System.in reads characters in one by one. You attach System.in to another stream that will accumulate the characters into a word 9

Input/Output System.err implements the standard error stream. This is used to send error messages to you as the program is executing. E.g. - to the console. E.g. The is the screen at the bottom of the Jgrasp program where you can see your errors. 10

Streams Any source of input or destination for output is called a stream. You must import into your program import java.io 11

Exceptions Exceptions are thrown by a program, and may be caught and handled by another part of the program. A program can therefore be separated into a normal execution flow - your program runs exception execution flow – an exception stops the program and may start another flow and an exception execution flow – an exception stops the program and may start another flow 12

13 Exception Not to Catch public class Zero { public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println (numerator / denominator);// } // method main } // class Zero // produces a division by 0 error An error – division by 0 - represents a unrecoverable situation and should not be caught.

Exception Handling A program can deal with an exception in one of three ways: ignore it – ( which is sometimes very tempting) handle it where it occurs - preferred handle it an another place in the program The manner in which an exception is processed is an important design consideration. 14

Exception Handling If an exception is ignored by the program, If an exception is ignored by the program, the program will terminate and produce an appropriate message. E.g public static void main(String Args) throws IOException { ……. // reads in from a file and if an exception occurs // it throws the exception so the program will close …… } The program will terminate. The Exception was not caught but “ Thrown” 15

Throwing an Exception method call trail that leads to the line of code When the program terminates the call stack trace shows the method call trail that leads to the line of code that caused the problem. (line 40) E.g java.lang.NullPointerException at HPAirGUIApplet.init(HPAirGUIApplet.java:40) // your code problem occurred at line 40 in the applet 619 // and the operation that is the culprits is at java 424 etc at sun.applet.AppletPanel.run(AppletPanel.java:424) at java.lang.Thread.run(Thread.java:619 ) 16

public String myMethod() { try { // calls trickyMethod() …….. return trickyMethod(); // calls method and an exception //may occur here // // so catch it here and name it } catch ( IOException e ) // so catch it here and name it{ // // will print out the “bad data” (see next slide) System.out.println (e.getMessage()“) return null; } 17 BETTER WAY TO HANDLE EXCEPTION

trickyMethod throws the Exception back to the calling method trickyMethod can have an input exception: trickyMethod can have an input exception: public int trickyMethod() throws IOException { int result = readAnotherInt();// read in an int if ( result < 0 ) throw new IOException( "bad data" ); return result; } //So if result is less than 0, an exception is thrown //Execution goes back to the calling method ( myMethod()) //which prints out “bad data “ and then returns null – see previous slide 18

19 Type codes used in describing Exceptions LetterTypeParent Class Checked? (declare throws?) Use RRuntimejava.lang.RuntimeException Error that can occur in almost any code e.g. NullPointerException. EErrorjava.lang.Error Serious error you really should not try to catch, e.g. OutOfMemoryError. CCheckedjava.lang.Exception Checked exceptions are required by java to be handled e.g. EOFException. Exceptions come is several flavors: RuntimeExceptions, Errors, Checked and Unchecked.

Class Exception – pre-defined java class class Exception class Exception // defined in the java.io package { // will contain an error message to be printed out private String message;// contains error message // // a string which describes the exception is sent and stored in //“message” public Exception (String message public Exception (String message) // constructor { this.message = message; // user defined error message } // retrieve the String sent to the constructor to output public String getMessage() { return message:} 20

(Class got Milk) try { System.out.println("Enter number of donuts:"); donutCount = scan.nextInt(); System.out.println("Enter # of glasses of milk:"); milkCount =scan.nextInt(); if (milkCount < 1) { throw new Exception("Exception: No Milk!"); } // close try { more code } // creates an object of Exception object “e” catch(Exception e) // creates an object of Exception object “e”{ // line below will output “Exception:NoMilk”) // System.out.println(e.getMessage()) // prints “Exception:NoMilk” } // close catch } 21

TRY - Catch Exception is a predefined class and the throws statement creates a new object of the class Exception When the exception is thrown, the code in the surrounding try block stops executing and another portion of code - the catch block begins execution. 22

The parameter to the catch : catch (Exception e)  is preceded by a class name that specifies what kind of exception is thrown e.g.  Exception, or  FileNotFoundException 23

 In throws new Exception (“ Exception: No Milk”),  the string “Exception: no milk” is an argument to the constructor in the Exception class  and is stored in an instance variable message so it can be recovered with a getter method - e.getMessage(). 24

Catching the Exception When the exception is thrown, execution goes to the catch block: catch ( Exception e) { System.out.println(e.getMessage());// prints error message e.g; if we throw the exception with the string below throw new Exception("Exception: No Milk!");  So e.getMessage prints: “Exception: No Milk” 25

Throwing Exceptions back to calling method public void eatPizza() throws StomachAcheException ( ….. Some code ….. if (ateTooMuch()) { throw new StomachAcheException(“Ouch”); ….. }  When the StomachAcheException is thrown  we exit from the eatPizza() method and called from.  go back to where the method was called from.  If no exception is thrown, processing continues as normal to the code after the catch block. 26

USER DEFINED EXCEPTION class StomachAcheException class StomachAcheException // user defined exception { // will contain an error message to be printed out private String message;// contains error message // // a string which describes the exception is sent and stored in //“message” public Exception (String message public Exception (String message) // constructor { this.message = message; // user defined error message message = message + “ “ + “GET some alka seltzer” } // retrieve the String sent to the constructor to output public String getMessage() { } return message: } So the message contains “Ouch” + “ So the message contains “Ouch” + “GET some alka seltzer” 27

Types of Exceptions  I.Errors: When a dynamic linking failure or other "hardware" failure in the virtual machine occurs, the machine throws an Error. These are never thrown by the programmer. And the program terminates 28

. Runtime Exceptions  II. Runtime Exceptions: Subtypes of the RuntimeException class are unchecked exceptions – they represent exceptions that occur during runtime. “Unchecked “ means you are not required to catch them But good coding practices demand that you do. 29

Exceptions and Exception Types 30

Checked Exceptions An exception therefore is either checked or unchecked. checked or unchecked. A checked exception can only be thrown within a try block or within a method that is designated to throw that exception. 31

Checked Exceptions The compiler will complain if a checked exception is not handled appropriately. Checked exceptions are due to the environment which are beyond the programmers control must handle in their code but to which the programmer must handle in their code reading past the End of File E.g., EOFException (reading past the End of File), FileNotFoundException an incorrectly coded U MalFormedURLException (an incorrectly coded URL) 32

Exception - Making your own To define a class representing a new checked exception, ( you can write your own!!) the code is public class MyCheckedException extends Exception. Checked exceptions are checked by the compiler so you have no choice but to handle them in the code 33

Unchecked Exceptions no try/catch require An unchecked exception (no try/catch required) results from programming errors. results from programming errors. dividing by zero E.g. arithmetic exceptions such as dividing by zero ArithmeticException, ArrayIndexOutOfBounds Exception, NumberformatException, NullPointerException. 34

Unchecked Exceptions These do not require explicit handling, though good programmers do so. To define a class that will check these exceptions, Your new exception class must extend RunTime Exception. 35

Checked Exceptions- Catch or specify requirement  Java requires that a method either  catch or  specify all checked exceptions that are thrown within the scope of the method. e.g.Catch  A method can catch an exception by providing an exception handler for that type of exception. e.g.  a try /catch block 36

Catch or specify requirement Catch or specify requirement (con’d) Specify  If a method chooses not to catch an exception,  the method must specify that it can throw that exception.  E.g. in your method you can throw an exception without catching it anywhere in the program.  This is bad form!! 37

Runtime Exceptions - examples  I  I. Exceptions can be thrown within the method e.g The method handles the try/catch block  II. Exceptions can be thrown indirectly by the method through calls to other methods. E.g. Thus method1 calls method2 which throws an exception. Whether method2 handles it or throws it is a design issue. 38

Exception Propagation If it is not appropriate to handle the exception where it occurs, it can be handled at a higher level. The method will throw the exception in its header 39

Exceptions propagate Exceptions propagate up through the method calling hierarchy until they are caught and handled or or until they reach the outermost level. 40

Propagating Errors Up the Call Stack public Method1 { try { call method2; } catch (exception) { doErrorProcessing; } Method2 throws exception // exception thrown to calling method public Method2 throws exception // exception thrown to calling method { call method3; } public method3 throws exception // exception thrown back to calling method { call readFile; // this is where the exception can occur } 41

The try Block writing to a file: try{ /// try{ /// all IO require checked exceptions outFile = new PrintStream( new BufferedOutputStream (new FileOutputStream("Out.txt"))); for (int i = 0; i < size; i++) outFile.println("Value at: " + i + vector.elementAt(i)); } // close file } catch (NegativeArraySizeException e) { System.out.println(“Illegal argument “); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } 42

IMPORTANT Order of the listing of multiple exceptions: IF YOU PUT THE IOEXCEPTION FIRST IN THE ORDER, IF YOU HAVE A NegativeArraySizeException IT WILL BE CAUGHT BY THE IOEXCEPTION. IOEXCEPTION WILL CATCH ALL EXCEPTIONS AND YOU WILL NOT KNOW WHAT HAPPENED THIS WAS A QUESTION A GOOGLE INTERVIEWER ASKED. See slide 40 43

The finally Clause A try statement can have an optional clause designated by the reserved word finally. If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete. 44

finally clauses exception is generated, Also, if an exception is generated, the statements in the finally clauses are executed after the statements in the catch clause for that exception completes. 45

The statements within the finally block are always executed. Why? To provides a mechanism that allows your method to clean up after itself regardless of what happens within the try block. Use the finally block to close files or release other system resources. finally { System.out.println("Closing file"); outFile.close(); } YOU MUST SPECIFICALLY CLOSE AN OUTPUT FILE, OR THE DATA YOU WROTE TO IT IS LOST 46

ORDER OF EXCEPTIONS the order of the catch clauses to what you need to know. In this next example, the order of the catch clauses is according to what you need to know. if the file was not thereyou put that first If you need to know if the file was not there, then you put that first. then any IO exception could occur If you put IOException first, then any IO exception could occur and you would not know if the file was there. and you would not know if the file was there. 47

Order of Exceptions // exception CATCHES INCORRECT DATA // exception CATCHES INCORRECT DATA public void ReadFromFile try // read in an integer from a file { // read in an integer from a file units = scanner.nextInt(); units = scanner.nextInt(); } // close try NumberFormatException exception catch (NumberFormatException exception) { System.out.println ("Error in input. Line ignored:"); System.out.println (units); } // close catch 48

49 catch (FileNotFoundException exception) { System.out.println ("The file " + file + " was not found."); } // close catch // CATCHES ALL IO EXCEPTIONS catch (IOException exception){ // CATCHES ALL IO EXCEPTIONS System.out.println ( “ IOexception – problem with file”) System.out.println (exception); }// close catch // CATCHES ALL EXCEPTIONS catch (Exception e){ // CATCHES ALL EXCEPTIONS System.out.println (exception); }// close catch finally { outFile.close(); e.printStackTrace(); }