When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.

Slides:



Advertisements
Similar presentations
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Advertisements

CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 9 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
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.
Chapter 11  I/O and Exception Handling 1 Chapter 11 I/O and Exception Handling.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Lecture 7 File I/O (and a little bit about exceptions)‏
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Files and Streams CS 21a Chapter 11 of Horstmann.
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.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Chapter 14 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Chapter 10 – Input/Output and Exception Handling Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Week 12 – Text Files Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Java Programming Week 9: Input/Ouput and Exception Handling, Files and Streams (Chapter 11 and Chapter 19)
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
The Problem Unexpected erroneous situations are often discovered by code which is NOT prepared to remedy the error………. For example.. String in = JOptionPane.showInputDialog(“enter.
Exception Handling.
Java Exceptions a quick review….
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
CSE 501N Fall ’09 17: Exception Handling
Goals To read and write text files To process command line arguments
Chapter 11 – Input/Output and Exception Handling
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Chapter 15 – Exception Handling
Advanced Java Programming
Exceptions Handling the unexpected
Exception Handling and Reading / Writing Files
Exception Handling.
Web Design & Development Lecture 7
Chapter 11 Input/Output Exception Handling
Exceptions 19-Feb-19.
Exceptions 25-Apr-19.
Tutorial Exceptions Handling.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Presentation transcript:

When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case. −When the input or output file doesn't exist, a FileNotFoundException can occur −In our next sample program, we take the easy way out and terminate the main method if the exception occurs. −To throw the exception, label the main method like this: public static void main(String[] args) throws FileNotFoundException −In the following sections, we will learn how to deal with exceptions in a more professional way. FileNotFoundException 1

Reads all lines of a file and sends them to the output file, preceded by line numbers Sample input file: Mary had a little lamb Whose fleece was white as snow. And everywhere that Mary went, The lamb was sure to go! Program produces the output file: /* 1 */ Mary had a little lamb /* 2 */ Whose fleece was white as snow. /* 3 */ And everywhere that Mary went, /* 4 */ The lamb was sure to go! Program can be used for numbering Java source files A Sample Program 2

01: import java.io.FileReader; 02: import java.io.FileNotFoundException; 03: import java.io.PrintWriter; 04: import java.util.Scanner; 05: 06: public class LineNumberer 07: { 08: public static void main(String[] args) 09: throws FileNotFoundException 10: { 11: Scanner console = new Scanner(System.in); 12: System.out.print("Input file: "); 13: String inputFileName = console.next(); 14: System.out.print("Output file: "); 15: String outputFileName = console.next(); 16: 17: FileReader reader = new FileReader(inputFileName); 18: Scanner in = new Scanner(reader); 19: PrintWriter out = new PrintWriter(outputFileName); 20: int lineNumber = 1; ch11/fileio/LineNumberer.java Continued 3

21: 22: while (in.hasNextLine()) 23: { 24: String line = in.nextLine(); 25: out.println("/* " + lineNumber + " */ " + line); 26: lineNumber++; 27: } 28: 29: out.close(); 30: } 31: } ch11/fileio/LineNumberer.java (cont.) 4

There are two main aspects to exception handling: reporting and recovery −Point of reporting is usually far apart from the point of recovery Example: Assume that the get method of a class detects that a nonexistent element is being accessed. How the program decides what to do about this failure? −Should the user be asked to try a different operation? −Should the program be aborted after saving the user’s work? In Java exception handling provides a flexible mechanism for passing control from the point of error reporting to the point of competent recovery. When you detect an error condition, just throw an appropriate exception object to signal an exceptional condition and you are done. When an exception is thrown, method terminates immediately Execution continues with an exception handler Throwing Exceptions 5

public class BankAccount { public void withdraw(double amount) { if (amount > balance) { //what to do if someone trying to withdraw much money from a bank account } balance = balance - amount; }... } Throw an exception object to signal this exceptional condition −Java library provides many classes to signal all sorts of exceptional conditions −Look around for an exception type that might describe your situation In our example what about IllegalStateException or IllegalArgumentException: −Illegal state? Is the bank account is an illegal state for the witdraw operation? Not really −illegal argument value? It sounds more suitable Throwing Exceptions 6

Illegal parameter value IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception ; No need to store exception object in a variable: throw new IllegalArgumentException("Amount exceeds balance"); public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; }... } When an exception is thrown, method terminates immediately Execution continues with an exception handler Throwing Exceptions 7

Hierarchy of Exception Classes 8

 Checked oMajority of these exceptions occur when dealing with input and output ; i.e., IOException oWhen you throw these exceptions, compiler checks that you don't ignore them omust tell the compiler what you will to do about the exception when thrown. oThese exceptions are due to external circumstances that you cannot prevent  Unchecked oAll runtime exceptions are unchecked. oCompiler does not insist that your program be able to handle these conditions. oBut in your code you should test your references, your values, the format of your numbers before using them oRuntimeException (and its subclasses) or Error are an example NumberFormatException IllegalArgumentException NullPointerException oAnother Example of error: OutOfMemoryError Two types of exceptions : Checked and Unchecked 9

Categories aren't perfect: −Scanner.nextInt throws unchecked InputMismatchException −Checked exceptions would have been more appropriate because programmer cannot prevent users from entering incorrect input. −Designers made this choice to make the class easy to use for beginning programmers Deal with checked exceptions principally when programming with files and streams For example, use a Scanner to read a file String filename =...; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); But, FileReader constructor can throw a FileNotFoundException Checked and Unchecked Exceptions 10

You have two choices: 1.Handle the exception as will be explained next slides 2.Or tell compiler that you are aware of this error and you want your method to be terminated when the exception occurs To declare that a method should be terminated when a checked exceptions occurs, use throws specifier so it can throw an exception public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);... } −throws signals the caller of your method that it may encounter exception so caller needs to make a decision either to handle them or tell its caller that exception may be thrown. For multiple exceptions: public void read(String filename) throws IOException, ClassNotFoundException Checked and Unchecked Exceptions 11

Every exception should be handled somewhere in your program −No exception handler: an error message is printed and your program terminates −But you would not want a professionally written program to die because of some unexpected error. −There fore you should install exception handlers for all exceptions your program might throw. Install an exception handler with try/catch statement try block contains statements that may cause an exception catch clause contains handler for an exception type Catching Exceptions 12 try {... FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);... } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); }

Statements in try block are executed If no exceptions occur, catch clauses are skipped If exception of matching type occurs, execution jumps to catch clause If exception of another type occurs, it is thrown until it is caught by another try block Catching Exceptions-Example 13 try { String filename =...; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input);... } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); }

try { System.out.println("How old are you?"); int age = in.nextInt(); System.out.println("Next year, you'll be " + (age + 1)); } catch (InputMismatchException exception) { exception.printStackTrace(); } General Try Block another example 14 exception in catch clause contains reference to the exception object that was thrown catch clause can analyze object to find out more details exception.printStackTrace (): printout of chain of method calls that lead to exception

Occasionally you need to take some action whether or not an exception is thrown. Exception terminates current method Danger: Can skip over essential code −For example, it is important to close a PrintWriter to ensure that all output is written to the file, or an exception may be thrown before closing a reader filer. Example: reader = new FileReader(filename); Scanner in = new Scanner(reader); readData(in); reader.close(); // May never get here Must execute reader.close () even if exception happens Use finally clause for code that must be executed "no matter what" The finally Clause 15

FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } finally { reader.close(); // if an exception occurs, finally clause is // also executed before exception is passed // to its handler } The finally Clause 16 Finally clause is executed when try block is exited in any of three ways: −After last statement of try block −After last statement of catch clause, if this try block caught an exception −When an exception was thrown in try block and not caught Recommendation: don't mix catch and finally clauses in same try block

You can design your own exception types – subclasses of Exception or RuntimeException if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of " + balance); } Make it an unchecked exception – programmer could have avoided it by calling getBalance first Extend RuntimeException or one of its subclasses Supply two constructors 1.Default constructor 2.A constructor that accepts a message string describing reason for exception Designing Your Own Exception Types 17

public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} //default construct public InsufficientFundsException(String message) { super(message); } } Designing Your Own Exception Types 18