Exception Handling.

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

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
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.
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.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
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.
Lecture 27 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.
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.
Applets & Applications CSC 171 FALL 2001 LECTURE 15.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.
Java Software Solutions Foundations of Program Design Sixth Edition
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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 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 Week 9: Input/Ouput and Exception Handling, Files and Streams (Chapter 11 and Chapter 19)
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
(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.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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.
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
CS102 – Exceptions David Davenport Latest: May 2015
Chapter 12 Exception Handling and Text IO
CSE 501N Fall ’09 17: Exception Handling
Chapter 14: Exception Handling
Exceptions 10-Nov-18.
Chapter 15 – Exception Handling
EE422C Software Implementation II
Exception Handling Chapter 9.
Exceptions & exception handling
Exceptions Handling the unexpected
Exceptions & exception handling
Chapter 12 Exception Handling
Exception Handling and Reading / Writing Files
Part B – Structured Exception Handling
Web Design & Development Lecture 7
Chapter 11 Input/Output Exception Handling
Exceptions 19-Feb-19.
Chapter 12: Exceptions and Advanced File I/O
Exceptions 25-Apr-19.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
CSC 143 Java Errors and Exceptions.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
Exception Handling.
Exceptions Review Checked Vs. Unchecked Exceptions
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

Error Handling Traditional approach: Method returns error code Problem: Forget to check for error code Failure notification may go undetected Problem: Calling method may not be able to do anything about failure Program must fail too and let its caller worry about it Many method calls would need to be checked Continued…

Error Handling (Cont’d) Instead of programming for success You would always be programming for failure: x.doSomething() if (!x.doSomething()) return false;

Throwing Exceptions Exceptions: Can't be overlooked Sent directly to an exception handler–not just caller of failed method Throw an exception object to signal an exceptional condition Example: IllegalArgumentException: illegal parameter value IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; Continued…

Throwing Exceptions (Cont’d) No need to store exception object in a variable: When an exception is thrown, method terminates immediately Execution continues with an exception handler throw new IllegalArgumentException("Amount exceeds balance");

Exception Handling: An Example public class BankAccount { public void withdraw(double amount) { if (amount > balance) { IllegalArgumentException exception = new IllegalArgumentException("Amount exceeds balance"); throw exception; } balance = balance - amount; } . . . }

Hierarchy of Exception Classes Figure 1: The Hierarchy of Exception Classes

Hierarchy of Exception Classes (Cont’d) Figure 2: The Hierarchy of Exception Classes

Hierarchy of Exception Classes (Cont’d) Figure 3: The Hierarchy of Exception Classes

Hierarchy of Exception Classes (Cont’d) Figure 4: The Hierarchy of Exception Classes

Syntax: Throwing an Exception  throw exceptionObject; Example:  throw new IllegalArgumentException(); Purpose: To throw an exception and transfer control to a handler for this exception type

Simple: only constructor methods. The Exception Class Simple: only constructor methods. Figure 5: The Exception Class

Handling Exceptions When an exception occurs, an object will throw an exception. The exception handler, possibly the same object, will catch it. Figure 6: Flow of Handling Exceptions

Example: Two Classes Throw in one class... …Catch in the other. Figure 7: Flow of Handling Exceptions

Checked and Unchecked Exceptions Two types of exceptions: Checked: The compiler checks that you don't ignore them Due to external circumstances that the programmer cannot prevent Majority occur when dealing with input and output For example, IOException

Checked and Unchecked Exceptions (Cont’d) Two types of exceptions: Unchecked: Extend the class RuntimeException or Error They are the programmer's fault Examples of runtime exceptions: Example of error: OutOfMemoryError NumberFormatException IllegalArgumentException NullPointerException

Checked and Unchecked Exceptions (Cont’d) Categories aren't perfect: Scanner.nextInt throws unchecked InputMismatchException Programmer cannot prevent users from entering incorrect input This choice makes the class easy to use for beginning programmers Deal with checked exceptions principally when programming with files and streams

Checked and Unchecked Exceptions (Cont’d) For example, use a Scanner to read a file But, FileReader constructor can throw a FileNotFoundException String filename = . . .; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader);

Checked and Unchecked Exceptions (Cont’d) Two choices for dealing with exceptions in a method A: Handle the exception (use try-catch within Method A) Tell compiler that you want method A to be terminated when the exception occurs Use throws specifier so method A can throw a checked exception Handle the exception from Method B that called A Or Method C that called Method B that called Method A. …and so on. public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); . . . }

Checked and Unchecked Exceptions (Cont’d) For multiple exceptions: Keep in mind inheritance hierarchy: If method can throw an IOException and FileNotFoundException, make sure you catch the FileNotFoundException before the IOException. WHY? public void read(String filename) throws IOException, ClassNotFoundException

An Example: NumberFormatException When expecting integer inputs, if the user types a non-integer number, then an exception of type NumberFormatException is thrown!

Syntax: Exception Specification accessSpecifier returnType methodName(parameterType parameterName, . . .) throws ExceptionClass, ExceptionClass, . . . Example:  public void read(BufferedReader in) throws IOException Purpose: To indicate the checked exceptions that this method can throw

Catching Exceptions 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 (Cont’d) Example: 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"); }

Catching Exceptions (Cont’d) 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 Continued…

Catching Exceptions (Cont’d) catch (IOException exception) block exception 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

Syntax: General Try Block statement . . . } catch (ExceptionClass exceptionObject) {

Syntax: General Try Block (Cont’d) Example:  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(); Purpose: To execute one or more statements that may generate exceptions. If an exception occurs and it matches one of the catch clauses, execute the first one that matches. If no exception occurs, or an exception is thrown that doesn't match any catch clause, then skip the catch clauses.