Special error return Constructors do not have a return value What if method uses the full range of the return type?

Similar documents
23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Chapter 10. IO Streams

Darshan Institute of Engineering & Technology for Diploma Studies

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Java Input / Output. CSE 413, Autumn 2002 Programming Languages.

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

Software 1 with Java. Recitation No. 7 (Java IO) May 29,

Software 1. Java I/O

CS 251 Intermediate Programming Java I/O Streams

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

PIC 20A Streams and I/O

Software 1 with Java. Recitation No. 9 (Java IO) December 10,

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

Exceptions and Working with Files

I/O Streams. Object-oriented programming

IT101. File Input and Output

Sri Vidya College of Engineering & Technology Question Bank

The I/O Package. THE Java platform includes a number of packages that are concerned with the CHAPTER20

The Java I/O System. Binary I/O streams (ASCII, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

CSC 1214: Object-Oriented Programming

I/O streams. Byte Streams Character Streams InputStream ByteArrayInputStream FileInputStream FilterInputStream

Java Input/Output. 11 April 2013 OSU CSE 1

Introduction Unit 4: Input, output and exceptions

Objec&ves. Review. Standard Error Streams

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

תוכנה 1 תרגול 8 קלט/פלט רובי בוים ומתי שמרת

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Object-Oriented Programming in the Java language

Lecture 11.1 I/O Streams

CS193j, Stanford Handout #26. Files and Streams

CSB541 Network Programming 網路程式設計. Ch.2 Streams 吳俊興國立高雄大學資訊工程學系

Byte and Character Streams. Reading and Writing Console input and output

File Operations in Java. File handling in java enables to read data from and write data to files

Object Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

Object-Oriented Programming Design. Topic : Streams and Files

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

Object-Oriented Design. March 2005 Object Oriented Design 1

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

Software 1. תרגול 9 Java I/O

Chapter 10 Input Output Streams

CSD Univ. of Crete Fall Files, Streams, Filters

Performing input and output operations using a Byte Stream

ITI Introduction to Computer Science II

Files and IO, Streams. JAVA Standard Edition

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Example: Copying the contents of a file

Objec&ves STANDARD ERROR. Standard Error Streams. Ø Byte Streams Ø Text Streams 10/5/16. Oct 5, 2016 Sprenkle - CSCI209 1

C17: File I/O and Exception Handling

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Chapter 4 Java I/O. X i a n g Z h a n g j a v a c o s q q. c o m

1.00 Lecture 30. Sending information to a Java program

Techniques of Java Programming: Streams in Java

Programming Languages and Techniques (CIS120)

CSPP : Introduction to Object-Oriented Programming

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

The Decorator Pattern. Design Patterns In Java Bob Tarr

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

Events and Exceptions

Chapter 17 Binary I/O. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

CN208 Introduction to Computer Programming

WOSO Source Code (Java)

Basic Java IO Decorator pattern Advanced Java IO. Java IO - part 2 BIU OOP. BIU OOP Java IO - part 2

Simple Java Input/Output

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

Core Java Contents. Duration: 25 Hours (1 Month)

1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

Writing usable APIs in practice

Here is a hierarchy of classes to deal with Input and Output streams.

Input from Files. Buffered Reader

Programming Languages and Techniques (CIS120)

BBM 102 Introduction to Programming II Spring Exceptions

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Streams and File I/O

HST 952. Computing for Biomedical Scientists Lecture 8

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

输 入输出相关类图. DataInput. DataOutput. java.lang.object. FileInputStream. FilterInputStream. FilterInputStream. FileOutputStream

Full file at Chapter 2 - Inheritance and Exception Handling

Software Practice 1 - File I/O

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

Introductory Programming Exceptions and I/O: sections

Algorithms. Produced by. Eamonn de Leastar

Java IO and C++ Streams

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

Chettinad College of Engineering & Technology Department of Information Technology Internal Examination II (Answer Key)

Programmierpraktikum

2.6 Error, exception and event handling

QUESTION BANK. SUBJECT CODE / Name: CS2311 OBJECT ORIENTED PROGRAMMING

Transcription:

23 Error Handling Exit program (System.exit()) usually a bad idea Output an error message does not help to recover from the error Special error return Constructors do not have a return value What if method uses the full range of the return type? Call a user defined error handler awkward What must this method do? Exceptions! OODS 1997-2000 Michael Golm Error Handling 23.124 23.1 What is Exception Handling? Transfer control from error origin to error handler A.m() B.n() C.p() Responsibilities: Code author can detect the error but doesn t know how to handle it. Code user can handle the error but cannot detect it. OODS 1997-2000 Michael Golm Error Handling 23.125

23.1 What happens when a method is called? class Customer { void createaccount(bank bank) { Account account = new Account(); bank.newaccount(account, 5); class Bank { void newaccount(account a, int i) { int counter = 0; class Main { public static void main(string args[]) { Customer c = new Customer(); c.createaccount(new Bank()); Stack frame of main args c Stack parameter variable local variable OODS 1997-2000 Michael Golm Error Handling 23.126 23.1 What happens when a method is called? class Customer { void createaccount(bank bank) { Account account = new Account(); bank.newaccount(account, 5); class Bank { void newaccount(account a, int i) { int counter = 0; class Main { public static void main(string args[]) { Customer c = new Customer(); c.createaccount(new Bank()); Stack frame of createaccount Stack frame of main bank account args c Stack parameter variable (bank) local variable (account) parameter variable local variable OODS 1997-2000 Michael Golm Error Handling 23.127

23.1 What happens when a method is called? class Customer { void createaccount(bank bank) { Account account = new Account(); bank.newaccount(account, 5); class Bank { void newaccount(account a, int i) { int counter = 0; class Main { public static void main(string args[]) { Customer c = new Customer(); c.createaccount(new Bank()); Stack frame of newaccount Stack frame of createaccount Stack frame of main account 5 0 bank account args c Stack parameter variable (a) parameter variable (i) local variable (counter) parameter variable (bank) local variable (account) parameter variable local variable OODS 1997-2000 Michael Golm Error Handling 23.128 23.1 What happens when a method is called? class Customer { void createaccount(bank bank) { Account account = new Account(); bank.newaccount(account, 5); class Bank { void newaccount(account a, int i) { int counter = 0; class Main { public static void main(string args[]) { Customer c = new Customer(); c.createaccount(new Bank()); Stack frame of createaccount Stack frame of main bank account args c Stack parameter variable (bank) local variable (account) parameter variable local variable OODS 1997-2000 Michael Golm Error Handling 23.129

23.1 What happens when a method is called? class Customer { void createaccount(bank bank) { Account account = new Account(); bank.newaccount(account, 5); class Bank { void newaccount(account a, int i) { int counter = 0; class Main { public static void main(string args[]) { Customer c = new Customer(); c.createaccount(new Bank()); Stack frame of main args c Stack parameter variable local variable OODS 1997-2000 Michael Golm Error Handling 23.130 23.1 What happens when a method is called? class Customer { void createaccount(bank bank) { Account account = new Account(); bank.newaccount(account, 5); class Bank { void newaccount(account a, int i) { int counter = 0; class Main { public static void main(string args[]) { Customer c = new Customer(); c.createaccount(new Bank()); Stack OODS 1997-2000 Michael Golm Error Handling 23.131

23.2 Try, Throw, and Catch try { if () throw new MyException(); catch(myexception e) { // exception handler use throw to thow an exception catch block must immediately follow try block there can be more than one catch block catch blocks are matched in program order a method may not catch all exceptions uncatched exceptions are automatically thrown up the stack OODS 1997-2000 Michael Golm Error Handling 23.132 23.3 Finally the finally block is executed if the try block was entered can be used to clean up in case of (un-)catched exceptions try { catch() { // error handling finally { // release resources a finally block can also be used without catch try { if () return; finally { OODS 1997-2000 Michael Golm Error Handling 23.133

23.4 throws Exceptions must be declared in method header class Test { void m() throws MyException { if () throw new MyException(); OODS 1997-2000 Michael Golm Error Handling 23.134 23.5 Error Classes All exceptions are derived from Throwable Exceptions that can be expected nearly everywhere: Error: Linker errors, errors in the format of class files, out of memory, RuntimeException: array index, null pointer, illegal cast, arithmetic, Application-program exceptions are derived from java.lang.exception Throwable getmessage() Exception Error needs not to be declared or catched RuntimeException OODS 1997-2000 Michael Golm Error Handling 23.135

23.6 Exceptions and Inheritance: Catching Catching exception subclasses with multiple catch blocks Notice: Superclasses match all subclasses, catch superclasses at last class MathException { class ZeroDivideException extends MathException { class InvalidArgException extends MathException { try { catch(zerodivideexception e) { catch(invalidargexception e) { catch(mathexception e) { OODS 1997-2000 Michael Golm Error Handling 23.136 23.6 Example class TestException extends Exception { public TestException(String s) {super(s); public class Test { public void hello() throws TestException { if () throw new TestException("an error description"); public void testit() { try { hello(); catch (TestException t) { System.out.println("Exception raised:" + t.getmessage()); finally { // clean up OODS 1997-2000 Michael Golm Error Handling 23.137

23.7 Exceptions and Inheritance: Throwing Can overriding method throw other exceptions than the original method? Principle: Subclasses can be used wherever a superclass is expected. Subclasses are "better" than superclasses. This means: Subclass must not throw more exceptions than superclass. Subclass may throw subclasses of the superclass-thrown exceptions. Subclass must not throw superclasses of the exceptions. OODS 1997-2000 Michael Golm Error Handling 23.138 23.8 Example class E1 extends Exception { class E2 extends Exception { class E3 extends E2 { class A { void m() throws E2 { class B extends A { void m() throws??? {??? = OODS 1997-2000 Michael Golm Error Handling 23.139

23.8 Example class E1 extends Exception { class E2 extends Exception { class E3 extends E2 { class A { void m() throws E2 { class B extends A { void m() throws??? {??? = Wrong: E1 Exception Correct: E2 E3 none OODS 1997-2000 Michael Golm Error Handling 23.140 23.9 Summary Throwing an exception: throw new MyException(""); Block that may throw exceptions: try { Handling exceptions: try { throw new MyException(""); catch(myexception e) { Additionally: finally block Exceptions must be subclasses of Throwable. Application exceptions should be subclasses of Exception. Exceptions must be declared in the method header with throws OODS 1997-2000 Michael Golm Error Handling 23.141

24 The Java IO System Basic concept: streams Byte streams (InputStream/OutputStream) Charater streams (Reader/Writer) OODS 1997-2000 Michael Golm The Java IO System 24.142 24.1 Byte Streams User Data Source read() Byte- Stream InputStream write() Byte- Stream OutputStream Data Sink OODS 1997-2000 Michael Golm The Java IO System 24.143

24.2 Stream Specializations Where do the data come from / go to? File FileInputStream FileOutputStream OODS 1997-2000 Michael Golm The Java IO System 24.144 24.2 Stream Specializations Where do the data come from / go to? File FileInputStream ByteArrayInputStream byte[] FileOutputStream ByteArrayOutputStream OODS 1997-2000 Michael Golm The Java IO System 24.145

24.2 Stream Specializations Where do the data come from / go to? File FileInputStream ByteArrayInputStream byte[] FileOutputStream ByteArrayOutputStream SocketInputStream Internet SocketOutputStream OODS 1997-2000 Michael Golm The Java IO System 24.146 24.2 Stream Specializations Where do the data come from / go to? File FileInputStream ByteArrayInputStream byte[] FileOutputStream ByteArrayOutputStream SocketInputStream? Internet SocketOutputStream OODS 1997-2000 Michael Golm The Java IO System 24.147

24.3 Input Streams Class Diagram InputStream ByteArrayInputStream FileInputStream PipedInputStream FilterInputStream SequenceInputStream DataInput ObjectInput BufferedInputStream PushbackInputStream DataInputStream ObjectInputStream OODS 1997-2000 Michael Golm The Java IO System 24.148 24.4 FileInputStream, FileOutputStream Read from a file import java.io.*; public class Test { public static void main (String argv[]) throws IOException { FileInputStream f = new FileInputStream ("/tmp/test"); byte buf[] = new byte[4]; f.read(buf); OODS 1997-2000 Michael Golm The Java IO System 24.149

24.5 Combining Streams Create comfortable streams from simple streams The comfortable stream wraps the simple stream Decorator Design-Pattern OODS 1997-2000 Michael Golm The Java IO System 24.150 24.6 Combining Streams User Data Source Byte- Stream read() InputStream OODS 1997-2000 Michael Golm The Java IO System 24.151

24.7 Combining Streams User readint() Data Source Byte- Stream InputStream DataInputStream OODS 1997-2000 Michael Golm The Java IO System 24.152 24.8 DataInputStream InputStream rather uncomfortable DataInputStream used to read binary representation of data (int, float,) can be created from every InputStream InputStream in = new FileInputStream ("/tmp/test"); DataInputStream datain = new DataInputStream(in); float f = datain.readfloat(); readline() can be used to read whole lines for(;;) { String s = datain.readline(); System.out.println(s); OODS 1997-2000 Michael Golm The Java IO System 24.153

24.9 Reader/Writer Character streams for input/output (Reader, Writer) User Data- Source Character- Stream read() Reader write() Writer Character- Stream Data- Sink Character streams contain Unicode characters (16 bit) OODS 1997-2000 Michael Golm The Java IO System 24.154 24.10 Reader important methods: int read() Read one character and return it as int. int read(char buf[]) Read characters into buffer. Return number of read characters or -1 in case of error. int read(char buf[], int offset, int len) Read len characters in buffer buf starting at offset. long skip(long n) Skip n characters. void close() Closes the stream. OODS 1997-2000 Michael Golm The Java IO System 24.155

24.10.1FileReader Used to read from file Constructors: FileReader(String filename) FileReader(File file) FileReader(FileDescriptor fd) No additional methods (only inherited fom InputStreamReader) What is an InputStreamReader? OODS 1997-2000 Michael Golm The Java IO System 24.156 24.11 Byte Streams and Character Streams Convert byte streams to character streams using an encoding Encoding Local Unicode A B User Data- Source Byte- Byte- Character- Stream Stream Stream InputStream InputStreamReader read() Reader some encodings: "Basic Latin", "Greek", "Arabic", "Gurmukhi" OODS 1997-2000 Michael Golm The Java IO System 24.157

24.12 Buffered IO Reading/writing single characters can be expensive. Converting encodings can be expensive. Use BufferedReader, BufferedWriter if possible. BufferedReader can be created from every other Reader. Important method of BufferedWriter: void flush(): Empties the buffer - writes buffer to unbuffered writer. Buffer User read() Data- Source Reader BufferedReader OODS 1997-2000 Michael Golm The Java IO System 24.158 24.13 Buffered IO BufferedReader can read whole lines: String readline() BufferedReader in = new BufferedReader(new FileReader("test.txt")); String line = in.readline(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = in.readline(); OODS 1997-2000 Michael Golm The Java IO System 24.159

24.14 PrintWriter Can be created from every OutputStream or Writer println(string s): write string and end-of-line character(s) Example: Read file and print it to standard output import java.io.*; public class CopyStream { public static void main(string a[]) throws Exception { BufferedReader in = new BufferedReader( new FileReader("test.txt")); PrintWriter out = new PrintWriter(System.out); for(string line; (line = in.readline())!=null;) { out.println(line); out.close(); OODS 1997-2000 Michael Golm The Java IO System 24.160 24.15 FileWriter used to write characters to a file invoke close() after you finished writing! OODS 1997-2000 Michael Golm The Java IO System 24.161