Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

Slides:



Advertisements
Similar presentations
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Advertisements

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
© 2012 Pearson Education, Inc. All rights reserved. Chapter 12: Exceptions and Advanced File I/O Starting Out with Java: From Control Structures through.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Starting Out With Java 5 (Early Objects) Chapter 10 By Tony Gaddis Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
12-2 Chapter Topics Chapter 12 discusses the following main topics: Part I: Exceptions Handling Exceptions Throwing Exceptions Part II: More about Input/Output.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
COP INTERMEDIATE JAVA Exception Handling Serialization.
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:
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.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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
Preventing and Correcting Errors
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 10 Exceptions and Advanced File I/O.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Copyright © Curt Hill Error Handling in Java Throwing and catching 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.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 12: Exceptions and Advanced File I/O
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Chapter 11—Exceptions Handling Exceptions Throwing Exceptions.
Chapter 11: Exceptions and Advanced File I/O
Topics Introduction to File Input and Output
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
Handling Exceptions.
Chapter 12: Exceptions and Advanced File I/O
Topics Introduction to File Input and Output
Presentation transcript:

Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.

2 Chapter Topics Today –Exceptions –Handling Exceptions –Throwing Exceptions Thursday More about Input/Output Streams Advanced Topics: –Binary Files, –Random Access Files, and –Object Serialization

3 Exceptions An exception is an object that is generated as the result of an error or an unexpected event. Unhandled exceptions cause programs to bomb. This is not a good thing, particularly if the program is flying a plane or administering radiation, or running a nuclear reactor. Exceptions are runtime errors.

4 Handling Exceptions In Java, exceptions are said to have been “thrown.” In other languages, they may be “raised.” It is the programmers responsibility to write code that anticipates the occurrence of an exception and keeps the program from crashing. The code that does this is said to “handle” the exception and is called an exception handler. If the programmer doesn’t write code to “handle the exception”, the default exception handler does. It prints an error message and crashes the program which isn’t very satisfactory.

5 Exception Classes Object Throwable ExceptionError RuntimeExceptionIOException FileNotFoundExceptionEOFException … … … …

6 Handling Exceptions To handle an exception, you use a try catch block try { (try block statements...) } catch (ExceptionType ParameterName) { (catch block statements...) } try indicates the code that might cause an exception to occur catch indicates the exception that you expect to catch and how you want to handle it.

7 Catch Blocks A catch clause begins with the key word catch and has a parameter list consisting of the type of the exception and a variable name. catch (ExceptionType ParameterName) The code between the required curly braces following the catch clause will be executed if the try block throws the referenced exception. The Java Virtual Machine searches for a catch clause that can deal with the exception.

8 Handling Exceptions Each exception object has a method named getMessage that can be used to retrieve the default error message for the exception. Example: –ExceptionMessage.javaExceptionMessage.java

9 Handling Exceptions The parameter must be of a type that is compatible with the thrown exception’s type. After an exception is handled, the program will leave the catch block and continue execution at the point following it.

10 Polymorphic References To Exceptions When handling exceptions, you can use a polymorphic reference as a parameter in the catch clause but do not do so in this course. The exceptions that you must handle are the checked exceptions. They are derived from the Exception class. There are unchecked exceptions derived from RuntimeException which can be ignored but you should not ignore them in this course. A catch clause that uses a parameter variable of the Exception type is capable of catching any exception that is derived from the Exception class.

11 Handling Multiple Exceptions The code in the try block may be capable of throwing more than one type of exception. A catch clause needs to be written for each type of exception that could potentially be thrown. The JVM will run the first compatible catch clause found.

12 Exception Handlers A try statement may have only one catch clause for each specific type of exception. try { number = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println("Bad number format."); } catch (NumberFormatException e) // ERROR!!! { System.out.println(str + " is not a number."); }

13 Exception Handlers The NumberFormatException class is derived from the IllegalArgumentException class. try { number = Integer.parseInt(str); } catch (IllegalArgumentException e) { System.out.println("Bad number format."); } catch (NumberFormatException e) // ERROR!!! { System.out.println(str + " is not a number."); }

14 The finally Clause The try statement may have an optional finally clause. If present, the finally clause must appear after all of the catch clauses. try { (try block statements...) } catch (ExceptionType ParameterName) { (catch block statements...) } finally { (finally block statements...) }

15 The finally Clause The finally block is one or more statements, –that are always executed after the try block has executed and –that are always executed after any catch blocks have executed if an exception was thrown. The statements in the finally block execute whether an exception occurs or not.

16 The Stack Trace The call stack is an internal list of all the methods that are currently executing. A stack trace is a list of all the methods in the call stack. It indicates: –the method that was executing when an exception occurred and –all of the methods that were called in order to execute that method.

17 Uncaught Exceptions When an exception is thrown, it cannot be ignored. It must be handled by the program, or by the default exception handler. When the code in a method throws an exception: –normal execution of that method stops –the JVM searches for a compatible exception handler inside the method.

18 Uncaught Exceptions If there is no exception handler inside the method: –control of the program is passed to the previous method in the call stack. –If that method has no exception handler, then control is passed again, up the call stack, to the previous method. If control reaches the main method: –the main method must either handle the exception, or –the program is halted and the default exception handler handles the exception.

19 Checked and Unchecked Exceptions There are two categories of exceptions: –Unchecked – Checked. Unchecked exceptions derived from Error, which are thrown when a critical error occurs, should not be handled. Unchecked exceptions derived from RuntimeException should be handled or prevented. Checked exceptions derived from Exception do have to be handled by you.

20 Checked and Unchecked Exceptions If the code in a method can throw a checked exception, the method: –must handle the exception, or –it must have a throws clause listed in the method header. The throws clause informs the compiler what exceptions can be thrown from a method and avoids a compile time error

21 Checked and Unchecked Exceptions // This method will not compile! // No try/catch and no throws clause. public void displayFile(String name) { freader = new FileReader(name); inputFile = new BufferedReader(freader); input = inputFile.readLine(); while (input != null) { System.out.println(input); input = inputFile.readLine(); } inputFile.close(); }

22 Checked and Unchecked Exceptions The code in this method is capable of throwing checked exceptions. The keyword throws is written at the end of the method header, followed by a list of the types of exceptions that the method can throw. public void displayFile(String name) throws IOException,FileNotFoundException

23 Throwing Exceptions You can write code that: –throws one of the standard Java exceptions, or –an instance of a custom exception class that you have designed. The throw statement is used to manually throw an exception. throw new ExceptionType(MessageString); The throw statement causes an exception object to be created and thrown.

24 Throwing Exceptions The MessageString argument contains a custom error message that can be retrieved from the exception object’s getMessage method. If you do not pass a message to the constructor, the exception will have a null message. throw new Exception("Out of fuel"); –Note: Don’t confuse the throw statement with the throws clause. Example in text: DateComponentExceptionDemo.java DateComponentExceptionDemo.java

25 Creating Exception Classes You can create your own exception classes by deriving them from the Exception class or one of its derived classes. Example: –BankAccount.javaBankAccount.java –NegativeStartingBalance.javaNegativeStartingBalance.java –AccountTest.javaAccountTest.java

26 Creating Exception Classes Some examples of exceptions that can affect a bank account : These should be handled by program not as exceptions. –A negative starting balance is passed to the constructor. –A negative interest rate is passed to the constructor. –A negative number is passed to the deposit method. –A negative number is passed to the withdraw method. –The amount passed to the withdraw method exceeds the account’s balance. We can create exceptions that represent each of these error conditions but that would be stupid.

Tag in Documentation Comments General ExceptionName @author