Chapter 12 Exception Handling And Text IO

Slides:



Advertisements
Similar presentations
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
Advertisements

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 14 Exception Handling and Text.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 12 Exception Handling and Text.
1 Chapter 18 Exception Handling. 2 Motivations F Program runs into a runtime error –program terminates abnormally F How can you handle the runtime error.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
Exception Handling. Definition  The term exception is shorthand for the phrase "exceptional event.“  An exception is an event, which occurs during the.
COMP Exception Handling Yi Hong June 10, 2015.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Exceptions and Assertions Chapter 15 – CSCI 1302.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1)
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 12 Exceptions and File Input/Output
Java Exceptions a quick review….
Chapter 13 Exception Handling
Chapter 13 Exception Handling
Exception Handling in Java Reference: COS240 Syllabus
Topic: Exception Handling
Introduction to Exceptions in Java
Chapter 12 Exception Handling and Text IO
Exceptions 10-Nov-18.
Chapter 7 Exceptions and Assertions
Chapter 12 Exception Handling and Text IO
Chapter 14 Exception Handling and Text IO
Advanced Java Programming
Exceptions Handling the unexpected
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
CSS 161: Fundamentals of Computing
Chapter 12 Exception Handling
Chapter 11 Exception Handling and Text I/O
Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling and Text IO
Chapter 14 Exception Handling and Text IO
Chapter 13 Exception Handling
Chapter 12 Exception Handling and Text IO
Exceptions 25-Apr-19.
Tutorial Exceptions Handling.
Chapter 14 Exception Handling and Text IO
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Chapter 12 Exception Handling and Text IO
I/O Exceptions & Working with Files
Exceptions 10-May-19.
Chapter 12 Exception Handling and Text IO
Java Basics Exception Handling.
Exceptions 5-Jul-19.
Exception Handling.
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Presentation transcript:

Chapter 12 Exception Handling And Text IO ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH Introduction to Java Programming, Liang (Pearson 2014)

Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? Example You are working on Microsoft Word, and you try to open a file that does not exist OR is an incorrectly formatted .doc or .docx file (like someone tampered with it). What should happen? (a) Microsoft crashes (b) Microsoft alerts you of the issue (c) Forget Microsoft, Apple is superior!

Exception Types

System Errors System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

Checked Exceptions vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions. In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions.

Declaring, Throwing, and Catching Exceptions

Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException

Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new Exception(); Exception ex = new Exception(); throw ex;

Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }

Catching Exceptions try { statements; // Statements that may throw exceptions } catch (Exception1 exVar1) { handler for exception1; catch (Exception2 exVar2) { handler for exception2; ... catch (ExceptionN exVar3) { handler for exceptionN;

Catch or Declare Checked Exceptions Suppose p2 is defined as follows:

Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception, you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b).

The finally Clause try { statements; } catch(Exception ex) { handling ex; finally { finalStatements;

Cautions When Using Exceptions Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.

When to Throw Exceptions An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it. Often you can handle exception with if-else statements like we have previously seen. In this case, there is no need to throw.

Input and Output Input devices Output devices. Hard drive Mouse Microphone Network Keyboard Digital camera Input devices Output devices. Goal. Java programs that interact with the outside world. Java Libraries support these interactions We use the Operating System (OS) to connect our program to them Display Speakers Hard drive Printer MP3 Player Network

What have we seen so far? Standard output. Standard input. The OS output stream for text By default, standard output is sent to Terminal. Example: System.out.println() goes to standard output. Standard input. The OS input stream for text By default, standard input is received from the Terminal. Example: Scanner “Standard Draw.” Really a wrapper for Java’s GUI libraries Output to a window instead of a terminal Example: Draw a circle on the screen

FILE input and output

File Input We can reuse Scanner! Instead of “scanning” System.in, we scan a File. However we must: Import Scanner, File, and FileNotFoundException Modify our main function to handle a FileNotFoundException Scanner in = new Scanner( new File(“myfile.txt”)); in.nextInt(); in.nextDouble(); in.hasNext(); import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class MyProgram { public static void main(String[] args) throws FileNotFoundException { //Do something! } Note – alternative to throws, we could have done a try-catch block

File Output We can use PrintWriter Offers print, println, printf just like System.out PrintWriter out = new PrintWriter(“MyFile.txt”); out.println(“Hello FileIO World!”); Similarly we need to: Import PrintWriter and FileNotFoundException 1. import java.io.PrintWriter; Modify main to handle/throws FileNotFoundException

File Input/output Caveats Always call close after you are done using Scanner or PrintWriter Scanner in = new Scanner(new File(“MyFile.txt”)); //Use the Scanner as much //as you want in.close(); Call flush often on PrintWriter to ensure all output gets into the file. PrintWriter out = new PrintWriter(“MyFile.txt”); //Use the PrintWriter as much //as you want out.flush(); //Always flush after use! out.close();

For more information Google API Tutorials StackOverflow Practice, Practice, Practice!

Exercise – Work in triplets

Exercise Write a program that will generate 𝑁 random cirlces, where 𝑁∈[3, 20], the center 𝑥, 𝑦 points between −10, 10 , and the radius is between 1, 4 . Write the circles to a file – first line is 𝑁, each line after is the circle defined by 𝑥, 𝑦, and 𝑟 Write a program that reads your file and shows it to the user using StdDraw. Use a random color to show the outline and a different random color to fill the polygon. Augment your programs to Allow random rectangles as well. Randomly select circles/rectangles with 0.5 probability