CS 121 – Intro to Programming:Java - Lecture 12 Announcements New Owl assignment up soon (today?) For this week: read Ch 8, sections 0 -3 Programming assignment.

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

1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
Formal Language, chapter 4, slide 1Copyright © 2007 by Adam Webber Chapter Four: DFA Applications.
CS 206 Introduction to Computer Science II 01 / 20 / 2009 Instructor: Michael Eckmann.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
James Tam Exception handling in Java Java Exception Handling Dealing with errors using Java’s exception handling mechanism.
James Tam Simple file handling in Java Simple File Input And Output Types of Java files Simple file output in Java Simple file input in Java.
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.
CS 206 Introduction to Computer Science II 09 / 09 / 2009 Instructor: Michael Eckmann.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
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){...}
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Exception examples. import java.io.*; import java.util.*; class IO { private String line; private StringTokenizer tokenizer; public void newline(DataInputStream.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
CS 121 – Intro to Programming:Java - Lecture 10 Announcements Two Owl assignments up, due 17th, 22nd Another up today, due 11/30 Next programming assignment.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
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.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
COMP Exception Handling Yi Hong June 10, 2015.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 11: Handling Errors; File Input/Output.
CS 121 – Intro to Programming:Java - Lecture 7 Announcements A new Owl assignment is available. Programming assignment 4 is due on Thursday - hand in on.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
What/how do we care about a program? Robustness Correctness Efficiency (speed, space) 11/2/20151IT 179  Software Testing  Error Handling  Efficiency.
CS 121 – Intro to Programming:Java - Lecture 5 Announcements Course home page: Owl due Thursday at 11; another one up today. Third programming assignment.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
CS 121 – Intro to Programming:Java - Lecture 8 Announcements Current Owl assignment is due Wednesday. Next Owl assignment - arrays I - will be up by tomorrow.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
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.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
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.
CS 121 – Intro to Programming:Java - Lecture 4 Announcements Course home page: Owl due soon; another.
Data-Driven Programs Eric Roberts CS 106A February 26, 2016.
CS 121 – Intro to Programming:Java - Lecture 11 Announcements Inheritance Owl assignment due 11/30 at 11 am Programming assignment six due Friday 12/3.
Introduction to programming in java
Lecture Note Set 1 Thursday 12-May-05
Creating and Modifying Text part 2
CS Week 10 Jim Williams, PhD.
What/how do we care about a program?
Unit 6 Working with files. Unit 6 Working with files.
Chapter Four: DFA Applications
Exception Handling in Java
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Java Exception Very slightly modified from K.P. Chow
Why do we need exceptions?
Exceptions and Exception Handling
Presentation transcript:

CS 121 – Intro to Programming:Java - Lecture 12 Announcements New Owl assignment up soon (today?) For this week: read Ch 8, sections 0 -3 Programming assignment six due Friday 12/3 Last programming assignment up soon For Thursday: read the material on the StringTokenizer class

Today - We’ll cover two fairly complicated ideas: Exceptions - mechanics/bullet-proofing File io (the file stuff may spill over a bit into next week’s lecture)

Exceptions a uniform way to handle exceptional behavior a clean way to check for errors without cluttering code gives us an organizing protocol for thinking about errors gives a great boost to the principle of code reuse: a single class may be used differently in different applications, and the exception mechansism gives us a graceful way to allow for this. two kinds of exceptions: checked(IOEX) and unchecked(ArrayOutOF) Example: Imagine a text file of integers. If the file represents data from a deep space probe, doing something with the data - e.g. adding the numbers - would surely involve skipping over the occasional non-integer that’s present because deep space transmissions are funky.. But if the same file represents my bank account deposits, I don’t want to skip over that deposit of $134j9 !!

Checked exceptions - exceptions you must check for explitly Unchecked exceptions - mostly tied to potential logical errors- too complicated to check for (there are too many of them!) IOException - checked exception - we’ll see it at work soon.. ArrayIndexOutOfBoundsException - unchecked Exceptions are Objects! - You can create your own.. One important software development activity: bullet-proofing (idiot-proofing..)

The general form of the exception handling mechanism: try{ statement1 statement2 … } catch (Exceptionkind1 e){do stuff..} catch (Exceptionkind2 e){do stuff..} finally{blah blah}

public class BulletProof{ public static void main(String[] args){ ConsoleWindow c = new ConsoleWindow(); int scoreboard[] = new int[26]; for(int j = 0; j < 26; j++) scoreboard[j] = (int)(Math.random()*100); int n = 0, k = 0; boolean good = false; while (!good){ c.out.println("enter an index, I'll give you the value"); try { n = c.input.readInt(); k = scoreboard[n]; good = true;} catch(ArrayIndexOutOfBoundsException e){ c.out.println("out of bounds- try again"); } } c.out.println("contents of cell " + n + " is " + k); } }

import java.io.*; public class Echo{ String fname; //the text file name //the data buffer BufferedReader in_dat; public Echo(String data_file) throws IOException{ fname = data_file; File in_data = new File(fname); in_dat = new BufferedReader(new FileReader(in_data)); }

public void getLines() throws IOException { String line = in_dat.readLine(); while(line != null) { processLine(line); line = in_dat.readLine();} close_file(); } public void processLine(String line){ System.out.println(line); } public void close_file() throws IOException{ in_dat.close(); }

import java.io.*; import element.*; public class EchoTester{ public static void main(String[] args){ String fileName = “SumOfCubes.java”; try{ Echo e = new Echo(fileName); e.getLines(); } catch(IOException ex) {System.out.println(ex);} } }

œ´œ ----jGRASP exec: java EchoTester œœßœclass SumOfCubes{ œœßœ œœßœ œœßœ public int cubeSum(int k){ œœßœ int sum,cur,ones,tens, hundreds; œœßœcur = k; œœßœones = cur % 10; œœßœcur = cur / 10; œœßœtens = cur % 10; œœßœcur = cur / 10; œœßœhundreds = cur % 10; œœßœ return (cube(ones) + cube (tens) + cube(hundreds)); œœßœ } …

import element.*; import java.io.*; public class ConsoleEcho extends Echo{ ConsoleWindow d; ConsoleEcho(ConsoleWindow w,String f) throws IOException { super(f); d = w; } public void processLine(String line){ d.out.println(line); }

import java.io.*; import element.*; public class EchoTester{ public static void main(String[] args){ ConsoleWindow w = new ConsoleWindow(); w.out.println("enter name of a file from the current directory"); String fileName = w.input.readString(); try{ ConsoleEcho e = new ConsoleEcho(w,fileName); e.getLines(); } catch(IOException ex) {System.out.println(ex);} } }

œ´œ ----jGRASP exec: java EchoTester œœßœjava.io.FileNotFoundException: a;sdfhab (No such file or directory)

public class LineCount extends Echo{ ConsoleWindow d; private int count = 0; LineCount(ConsoleWindow w,String f) throws IOException { super(f); d = w; } public int getCount(){return count;} public void processLine(String line){ count++; } }

public class EchoTester{ public static void main(String[] args){ ConsoleWindow w = new ConsoleWindow(); w.out.println("enter name of a file from the current directory"); LineCount e = null; String fileName = w.input.readString(); try{ e = new LineCount(w,fileName); e.getLines(); } catch(IOException ex) {System.out.println(ex);} w.out.println(" line count in file is: " + e.getCount()); } }