Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.

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

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
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.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Catching Exceptions An exception may be thrown by a method when an exceptional occurance happens (and the method does not have the expertise to remedy.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
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.
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 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.
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.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Java Software Solutions Foundations of Program Design Sixth Edition
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Object Oriented Programming
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Input/Output and Exception Handling.
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
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.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Chapter 10 – Input/Output and Exception Handling 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)
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Exception Handling.
Chapter 10 – Exception Handling
CSE 501N Fall ’09 17: Exception Handling
Chapter 11 – Input/Output and Exception Handling
Exceptions 10-Nov-18.
Chapter 15 – Exception Handling
EE422C Software Implementation II
Exception Handling.
Chapter 11 Input/Output Exception Handling
Lecture 11 Objectives Learn what an exception is.
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
Exceptions 10-May-19.
Java Basics Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Exception Handling

Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between checked and unchecked exceptions To learn how to catch exceptions To know when and where to catch an exception

The finally clause Exception terminates current method Danger: Can skip over essential code 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 (Cont’d)

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 (Cont’d)

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

Syntax: The finally clause Try { statement... } finally { statement... }

Syntax: The finally clause (Cont’d) Example: FileReader reader = new FileReader(filename); try { readData(reader); } finally { reader.close(); } Purpose: To ensure that the statements in the finally clause are executed whether or not the statements in the try block throw an exception.

You can design your own exception types– subclasses of Exception or RuntimeException Make it an unchecked exception–programmer could have avoided it by calling the method getBalance() first Designing Your Own Execution Types if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of “ + balance); } Continued…

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 Execution Types (Cont’d)

public class InsufficientFundsException extends RuntimeException{ public InsufficientFundsException() { } public InsufficientFundsException(String message) { super(message); } } Designing Your Own Execution Types (Cont’d)

The Method printStackTrace() Used to determine the order in which the methods were called and where the exception was handled

The Method printStackTrace() (Cont’d) import java.io.*; public class PrintStackTraceExample1 { public static void main(String[] args) { try { methodA(); } catch (Exception e) { System.out.println(e.toString() + " caught in main"); e.printStackTrace(); } Continued…

The Method printStackTrace() (Cont’d) public static void methodA() throws Exception { methodB(); } public static void methodB() throws Exception { methodC(); } public static void methodC() throws Exception { throw new Exception("Exception generated " + "in method C"); } Continued…

Sample Run: The Method printStackTrace() (Cont’d) java.lang.Exception: Exception generated in method C caught in main java.lang.Exception: Exception generated in method C at PrintStackTraceExample1.methodC (PrintStackTraceExample1.java:30) at PrintStackTraceExample1.methodB (PrintStackTraceExample1.java:25) at PrintStackTraceExample1.methodA (PrintStackTraceExample1.java:20) at PrintStackTraceExample1.main (PrintStackTraceExample1.java:9)

Unfixable Error: If possible, it’s better to terminate the program abnormally than to allow the error to propagate. Normal versus Exceptional Code: The exception handler --- the catch block --- is distinct from the (normal) code that throws the exception --- the try block. Using an Exception: If your exception handler is not significantly different from Java’s, let Java handle it. Effective Design

Handling Exceptions.  Report the exception and terminate the program;  Fix the exceptional condition and resume normal execution.  Report the exception to a log and resume execution. Program Development. Exceptions help identify design flaws during program development. Report and Resume. Failsafe programs should report the exception and resume. Effective Design (Cont’d)

Defensive Design. Anticipate potential problems, especially potential input problems. Fixing an Exception. Handle fixable exceptions locally. This is both clearer and more efficient. Library Exception Handling. Many library classes leave exception handling to the application. Truly Exceptional Conditions. Use exceptions to handle truly exceptional conditions, not for expected conditions. Effective Design (Cont’d)

Summary of Important Points In Java, when an error occurs, you throw an Exception which is caught by exception handler code. A throw statement --- throw new Exception() --- is used to throw an exception. A try block is contains one or more statements that may throw an exception. Embedding a statement in a try block indicates your awareness that it might throw an exception and your intention to handle the exception.

Summary of Important Points (Cont’d) Checked exceptions must be caught or declared by the method in which they occur. Unchecked exceptions (subclasses of RuntimeException) are handled by Java if they are not caught in the program. A catch block contains statements that handle the exception that matches its parameter. A catch block can only follow a try block. There may be more than one catch block for each try block.

Summary of Important Points (Cont’d) The try/catch syntax separates the normal parts of an algorithm from special exceptional handling code. A method stack trace is a trace of a program’s method calls -- Exception.printStackTrace(). Static scoping: how the program is written. Depends on declarations and definitions. Dynamic scoping: how the program is executed. Depends on method calls.

Summary of Important Points (Cont’d) Finding a Catch Block: Search upward through the static scope, and backward through the dynamic scope. The Java Virtual Machine handles unchecked exceptions not caught by the program. Many Java library methods throw exceptions when an error occurs. Example: Java's integer division operator will throw an ArithmeticException if an attempt is made to divide by zero.

Summary of Important Points (Cont’d) Four ways to handle an exception:  Let Java handle it.  Fix the problem and resume the program.  Report the problem and resume the program.  Print an error message and terminate. The (optional) finally block contains code that will be executed whether an exception is raised or not. Exceptions should be used for exception truly exceptional conditions, not for normal program control. User-defined exceptions can extend the Exception class or one of its subclasses.

A Complete Program Program:  Asks user for name of file  File expected to contain data values  First line of file contains total number of values  Remaining lines contain the data  Typical input file:

What can go wrong?  File might not exist  File might have data in wrong format Who can detect the faults?  FileReader constructor will throw an exception when file does not exist  Methods that process input need to throw exception if they find error in data format Continued… A Complete Program (Cont’d)

What exceptions can be thrown?  FileNotFoundException can be thrown by FileReader constructor  IOException can be thrown by close method of FileReader  BadDataException, a custom checked exception class Continued… A Complete Program (Cont’d)

Who can remedy the faults that the exceptions report?  Only the main method of DataSetTester program interacts with user Catches exceptions Prints appropriate error messages Gives user another chance to enter a correct file A Complete Program (Cont’d)

File DataSetTester.java 01: import java.io.FileNotFoundException; 02: import java.io.IOException; 03: import java.util.Scanner; 04: 05: public class DataSetTester 06: { 07: public static void main(String[] args) 08: { 09: Scanner in = new Scanner(System.in); 10: DataSetReader reader = new DataSetReader(); 11: 12: boolean done = false; 13: while (!done) 14: { 15: try 16: { Continued…

File DataSetTester.java 17: System.out.println("Please enter the file name: "); 18: String filename = in.next(); 19: 20: double[] data = reader.readFile(filename); 21: double sum = 0; 22: for (double d : data) sum = sum + d; 23: System.out.println("The sum is " + sum); 24: done = true; 25: } 26: catch (FileNotFoundException exception) 27: { 28: System.out.println("File not found."); 29: } 30: catch (BadDataException exception) 31: { 32: System.out.println ("Bad data: " + exception.getMessage()); Continued…

File DataSetTester.java 33: } 34: catch (IOException exception) 35: { 36: exception.printStackTrace(); 37: } 38: } 39: } 40: }

The readFile method of the DataSetReader class Constructs Scanner object Calls readData method Completely unconcerned with any exceptions Continued…

The readFile method of the DataSetReader class If there is a problem with input file, it simply passes the exception to caller public double[] readFile(String filename) throws IOException, BadDataException // FileNotFoundException is an IOException { FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } Continued…

The readFile method of the DataSetReader class finally { reader.close(); } return data; }

The readFile method of the DataSetReader class Reads the number of values Constructs an array Calls readValue for each data value Checks for two potential errors  File might not start with an integer  File might have additional data after reading all values Makes no attempt to catch any exceptions private void readData(Scanner in) throws BadDataException { if (!in.hasNextInt()) throw new BadDataException("Length expected"); int numberOfValues = in.nextInt(); data = new double[numberOfValues]; for (int i = 0; i < numberOfValues; i++) readValue(in, i); if (in.hasNext()) throw new BadDataException("End of file expected"); }

The readFile method of the DataSetReader class Checks for two potential errors 1.File might not start with an integer 2.File might have additional data after reading all values Makes no attempt to catch any exceptions

The readFile method of the DataSetReader class private void readValue(Scanner in, int i) throws BadDataException { if (!in.hasNextDouble()) throw new BadDataException("Data value expected"); data[i] = in.nextDouble(); }

Scenario 1. DataSetTester.main calls DataSetReader.readFile 2. readFile calls readData 3. readData calls readValue 4. readValue doesn't find expected value and throws BadDataException 5. readValue has no handler for exception and terminates Continued…

Scenario 6. readData has no handler for exception and terminates 7. readFile has no handler for exception and terminates after executing finally clause 8. DataSetTester.main has handler for BadDataException ; handler prints a message, and user is given another chance to enter file name

File DataSetReader.java 01: import java.io.FileReader; 02: import java.io.IOException; 03: import java.util.Scanner; 04: 05: /** 06: Reads a data set from a file. The file must have // the format 07: numberOfValues 08: value1 09: value2 10:... 11: */ 12: public class DataSetReader 13: { Continued…

File DataSetReader.java 14: /** 15: Reads a data set. filename the name of the file holding the data the data in the file 18: */ 19: public double[] readFile(String filename) 20: throws IOException, BadDataException 21: { 22: FileReader reader = new FileReader(filename); 23: try 24: { 25: Scanner in = new Scanner(reader); 26: readData(in); 27: } 28: finally 29: { 30: reader.close(); 31: } Continued…

File DataSetReader.java 32: return data; 33: } 34: 35: /** 36: Reads all data. in the scanner that scans the data 38: */ 39: private void readData(Scanner in) throws BadDataException 40: { 41: if (!in.hasNextInt()) 42: throw new BadDataException("Length expected"); 43: int numberOfValues = in.nextInt(); 44: data = new double[numberOfValues]; 45: 46: for (int i = 0; i < numberOfValues; i++) 47: readValue(in, i); Continued…

File DataSetReader.java 48: 49: if (in.hasNext()) 50: throw new BadDataException("End of file expected"); 51: } 52: 53: /** 54: Reads one data value. in the scanner that scans the data i the position of the value to read 57: */ 58: private void readValue(Scanner in, int i) throws BadDataException 59: { Continued…

File DataSetReader.java 60: if (!in.hasNextDouble()) 61: throw new BadDataException("Data value expected"); 62: data[i] = in.nextDouble(); 63: } 64: 65: private double[] data; 66: }