Input-Output and Exception Handling

Similar documents
Exceptions - Example. Exceptions - Example

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Arrays and Basic Algorithms

Lecture 19 Programming Exceptions CSE11 Fall 2013

Introduction Unit 4: Input, output and exceptions

11/1/2011. Chapter Goals

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

Loops and Expression Types

CS159. Nathan Sprague

BBM 102 Introduction to Programming II Spring Exceptions

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

More on Exception Handling

Chapter 12 Exception Handling

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

I/O Streams. COMP 202 File Access. Standard I/O. I/O Stream Categories

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Defensive Programming. Ric Glassey

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

ITI Introduction to Computing II

ITI Introduction to Computing II

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

Introductory Programming Exceptions and I/O: sections

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

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

Motivations. Chapter 12 Exceptions and File Input/Output

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

More on Exception Handling

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSE 143 Lecture 25. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides adapted from Marty Stepp

Programming II (CS300)

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

C16b: Exception Handling

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Chapter 13 Exception Handling

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

CS159. Nathan Sprague

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

WOSO Source Code (Java)

BBM 102 Introduction to Programming II Spring 2017

Programming II (CS300)

CSE 143 Lecture 22. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp

CSE 143 Lecture 21. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp

Fundamentos de programação

COMP-202 Unit 9: Exceptions

Reading Text Files. 1 Reading from text files: Scanner

Full file at Chapter 2 - Inheritance and Exception Handling

Exceptions Handling Errors using Exceptions

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO

CN208 Introduction to Computer Programming

Data Structures. 03 Streams & File I/O

Simple Java Input/Output

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

CSPP : Introduction to Object-Oriented Programming

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Reading Input from Text File

COMP 213. Advanced Object-oriented Programming. Lecture 20. Network Programming

Projeto de Software / Programação 3 Tratamento de Exceções. Baldoino Fonseca/Márcio Ribeiro

C17: File I/O and Exception Handling

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Exceptions. Examples of code which shows the syntax and all that

Programming Languages and Techniques (CIS120)

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

More on Objects and Classes

An exception is simply an error. Instead of saying an error occurred, we say that an.

STREAMS. (fluxos) Objetivos

CISC 323 (Week 9) Design of a Weather Program & Java File I/O

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

EXCEPTIONS. Java Programming

ECE 122. Engineering Problem Solving with Java

Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

CIS 110: Introduction to Computer Programming

What are Exceptions?

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

Inheritance and Subclasses

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

CS 302: Introduction to Programming in Java. Lectures 17&18. It s insanely hot. People desperately need some snowflakes

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

EXCEPTIONS. Fundamentals of Computer Science I

HST 952. Computing for Biomedical Scientists Lecture 8

Programming Languages and Techniques (CIS120)

Exceptions and Libraries

CSCI 261 Computer Science II

Dining philosophers (cont)

CP122 CS I. Chapter 11: File I/O and Exceptions

When we reach the line "z = x / y" the program crashes with the message:

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

CS 3 Introduction to Software Engineering. 3: Exceptions

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Exception-Handling Overview

School of Informatics, University of Edinburgh

CS Week 11. Jim Williams, PhD

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Transcription:

Software and Programming I Input-Output and Exception Handling Roman Kontchakov / Carsten Fuhs Birkbeck, University of London

Outline Reading and writing text files Exceptions The try block catch and finally clauses Command line arguments Chapter 7 slides are available at www.dcs.bbk.ac.uk/ roman/sp1 SP1 2018-10 1

Reading Text Files class File (package java.io) describes disk files and directories (and has many methods, see API documentation) use the Scanner class for reading text files (package java.util) 1 File inputfile = new File("input.txt"); 2 Scanner in = new Scanner(inputFile); 3 while (in.hasnextline()) { 4 String line = in.nextline(); 5 //... now process the line... 6 } 7 in.close(); // close the file 8 // when you are done processing it SP1 2018-10 2

Reading Files and Web Pages instances of Scanner can be constructed from (overloading) File, String or InputStream (System.in is an instance of InputStream) NB: new Scanner("input.txt") is not an error, it creates a scanner for the string 1 URL pageurl = new URL("http://www.dcs.bbk.ac.uk/"); 2 Scanner in = new Scanner(pageURL.openStream()); DIY web browser NB: backslashes in file names need to be escaped as \\ "c:\\project\\sp1\\sp1-10.pdf" SP1 2018-10 3

Writing Text Files class PrintWriter has familiar methods: print, println and printf instances can be constructed from File, OutputStream or String (file name!) 1 PrintWriter out = new PrintWriter("output.txt"); 2 out.println("hello, World"); 3 double totalprice = 2.99; 4 out.printf("total: %8.2f\n", totalprice); 5 out.close(); // close the file 6 // when you are done processing it SP1 2018-10 4

Reading Binary Data 1 InputStream ins = new FileInputStream("shakira.mp3"); 2 int nextbyte; 3 while ( (nextbyte = ins.read())!= -1 ) { 4 // read a byte from ins, put it into nextbyte, 5 // compare it with -1 (end of input) 6 7 //... now do something with nextbyte... 8 } 9 ins.close(); What about the = in the loop condition? SP1 2018-10 5

Operation Precedence () method call highest!, (type), type cast -, + unary minus/plus *, /, % multiplicative +, - additive <, <=, >=, > relational ==,!= equality && logical AND logical OR? : ternary ++, -- unary =, +=, -=, *=, /=, %=,... assignment lowest SP1 2018-10 6

Operation Precedence (2) operators with higher precedence are evaluated before operators with relatively lower precedence What is the value of 2 + a % 3 if a is 11 NB: = is also an operation! 2 * 6 + a % 3 + 1 < 10 && a > 3 2 * 6 + a % 3 + 1 < 10 &&!a > 3 2 + a / 3 2 + (double) a / 3 b = 2 + a / 3 == 1? 4 : -4 SP1 2018-10 7

Operation Precedence: Example b = 2 + a / 3 == 1? 4 : -4 b 2 + a / 3 == 1? 4 : -4 2 + a / 3 == 1 4-4 2 + a / 3 1 2 a / 3 a 3 SP1 2018-10 8

Operation Associativity when two operators share an operand, the operator with the higher precedence goes first: 1 * 2 + 3 is treated as (1 * 2) + 3 1 + 2 * 3 is treated as 1 + (2 * 3) if an expression has two operators with the same precedence, the expression is evaluated according to its associativity: x = y = z = 17 is treated as x = (y = (z = 17)) NB: what is the effect of the following code? 1 boolean f = false; 2 if (f = true) 3 System.out.println("weird"); SP1 2018-10 9

Operation Associativity (2) unary operators (cast,!, -, etc.) have right-to-left associativity!!a is!(!a) assignment operators (=, +=, etc.) have right-to-left associativity a+= b+= 7 is a+= (b+= 7) conditional operator (?:) has right-to-left associativity all other operators have left-to-right associativity 1 System.out.println("1 + 2 = " + 1 + 2); 2 System.out.println("1 + 2 = " + (1 + 2)); 3 System.out.println(1 + 2 + " = 1 + 2"); SP1 2018-10 10

Exceptions an event that disrupts the normal flow of a program internal or fatal errors that happen rarely: OutOfMemory and other subclasses of Error unchecked exceptions are errors in the code: IndexOutOfBoundsException, NullPointerException, IllegalArgumentException and other subclasses of RuntimeException checked exceptions indicate something has gone wrong for an external reason beyond your control: IOException, FileNotFoundException and all other subclasses of Exception SP1 2018-10 11

Throwing Exceptions 1 if (amount > balance) { 2 // create and throw an exception object 3 throw new IllegalArgumentException 4 ("Amount exceeds balance"); 5 } 6 balance -= amount; when you throw an exception, processing continues in an exception handler SP1 2018-10 12

1 try { Catching Exceptions 2 // what if the file does not exist? 3 Scanner in = new Scanner(new File("name.txt")); 4 // what if the file is empty? 5 String input = in.next(); 6 // what if input is not an integer? 7 int value = Integer.parseInt(input); 8 } 9 catch (IOException e) { // class FileNotFoundException 10 e.printstacktrace(); // extends IOException 11 } 12 catch (NumberFormatException e) { 13 System.out.println("Input was not a number"); 14 } SP1 2018-10 13

Exception Classes Throwable getmessage(): String printstacktrace() Error Exception Checked Exceptions RuntimeException SP1 2018-10 14

Checked Exceptions external reason: IOException, FileNotFoundException, etc. the compiler makes sure that your program handles checked exceptions: either add a throws clause to a method that can throw a checked exception 1 public static String readfile(string filename) throws 2 FileNotFoundException { 3 Scanner in = new Scanner(new File(filename)); 4... 5 } or provide a handler for the exception some methods detect errors, some handle them, and some just pass them along SP1 2018-10 15

Call Stack: Example 1 public class CallStack { 2 private int i; 3 public static void m(callstack oo, int ii) { 4 oo.i = ii; 5 m((ii > 5)? oo : null, ii - 1); 6 } 7 public static void main(string[] args) { 8 CallStack o = new CallStack(); 9 try { 10 m(o, 8); 11 } 12 catch (NullPointerException e) { 13 System.out.println("o.i = " + o.i); 14 } 15 } 16 } SP1 2018-10 16

Call Stack Example: oo.i = ii; m((ii > 5)? oo : null, ii - 1); m(o,8) oo CallStack ii 8 oo.i = 8 i = 08 76 5 m(o,7) oo ii 7 oo.i = 7 m(o,6) oo ii 6 oo.i = 6 m(o,5) oo ii 5 oo.i = 5 m(null,4) oo ii null 4 NullPointerException SP1 2018-10 17

Call Stack Example: oo.i = ii; m((ii > 5)? oo : null, ii - 1); o CallStack i = 5 SP1 2018-10 18

The finally Clause 1 // the variable must be declared outside so that 2 // the finally clause can access it 3 PrintWriter out = new PrintWriter(filename); 4 try { 5 writedata(out); // may throw exceptions 6 } 7 finally { // this code is always executed: 8 out.close(); // the stream has to be closed 9 // even if an exception is thrown 10 } NB: do not use catch and finally in the same try statement put the above fragment into an outer try... catch... SP1 2018-10 19

Command Line Arguments programs that start from the command line receive the command line arguments in the main method consider a program CaesarCipher that encrypts or decrypts a file to another file java CaesarCipher input.txt output.txt args[] = { "input.txt", "output.txt" } java CaesarCipher -d input.txt output.txt args[] = { "-d", "input.txt", "output.txt" } SP1 2018-10 20

Command Line Arguments: Example 1 public static void main(string[] args) { 2... 3 for (String arg: args) { 4 if (arg.charat(0) == - ) { // command line 5 6 if (arg.charat(1) == d ) 7 key = -key; 8 else { 9 printusage(); 10 return; 11 } 12 } 13 else { // file name // option 14... see Section 7.3, pp. 331 332 SP1 2018-10 21

Command Line Arguments 1 public class Echo { // echoes command-line arguments 2 public static void main(string[] args) { 3 if (args.length == 0) return; // print nothing 4 // -n as first argument: no newline at the end 5 int start = args[0].equals("-n")? 1 : 0; 6 for (int i = start; i < args.length; i++) { 7 System.out.print(args[i]); 8 if (i == args.length - 1) { // last one? 9 if (! args[0].equals("-n")) 10 System.out.println(); 11 } 12 else System.out.print(" "); 13 } 14 } 15 } SP1 2018-10 22

Take Home Messages use Scanner for reading and PrintWriter for writing text files close all files when you are done processing them when an exception is thrown (throw statement), processing continues in an exception handler (catch clause) once a try block is entered, the statements in a finally clause are guaranteed to be executed checked exceptions are due to external circumstances programs that start from the command line receive the command line arguments in the main method SP1 2018-10 23