Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.

Slides:



Advertisements
Similar presentations
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Advertisements

CS102--Object Oriented Programming
Comp 249 Programming Methodology
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.
HST 952 Computing for Biomedical Scientists Lecture 7.
1 Week 11 l Basic Exception Handling »the mechanics of exceptions l Defining and Using Exceptions »some "simple" cases l Reality Check »guidelines for.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Review Linked list: Doubly linked list, insertback, insertbefore Remove Search.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
Exception Handling Chapter 8. Outline Basic Exception Handling Defining Exception Classes Using Exception Classes.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Chapter 9 Exception Handling Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
CS102--Object Oriented Programming Lecture 11: Exception Handling Copyright © 2008 Xiaoyan Li.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch Announcements l Project 6 now out. »Milestone due Oct. 24th »Final project.
Chapter 81 Exception Handling Chapter 8. 2 Reminders Project 5 due Oct 10:30 pm Project 3 regrades due by midnight tonight Discussion groups now.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
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.
Chapter 81 Exception Handling Chapter 8. 2 Objectives become familiar with the notion of exception handling learn Java syntax for exception handling learn.
Java Software Solutions Foundations of Program Design Sixth Edition
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Basics of Recursion l Programming with Recursion Recursion.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Java Programming: Guided Learning with Early Objects
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
COMP Exception Handling Yi Hong June 10, 2015.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
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.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Lecturer: Dr. AJ Bieszczad Chapter 8 COMP 150: Introduction to Object-Oriented Programming 8-1 l Basic Exception Handling »the mechanics of exceptions.
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.
Introduction to Exceptions in Java CS201, SW Development Methods.
Chapter 16 Exception Handling
Exceptions C++ Interlude 3
Chapter 14: Exception Handling
Announcements/Reminders
Exception Handling Chapter 9.
Exception Handling Chapter 8 Basic Exception Handling
Exception Handling Chapter 9 Edited by JJ.
COS 260 DAY 20 Tony Gauvin.
Exception Handling Chapter 8 Basic Exception Handling
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e
Basic Exception Handling
Presentation transcript:

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l Defining and Using Exceptions »some "simple" cases l Reality Check »guidelines for more realistic situations Exception Handling

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Exception Handling Overview l A way of organizing a program into sections for the normal case and the exceptional case »exception examples: division by zero incorrect type of input l A way of implementing programs incrementally »write & debug the code for normal operation first »add code for the exceptional case later l Simplifies development, testing, debugging and maintenance »errors are easier to isolate

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Warning : l The example programs in this chapter are simplified for instructional purposes l Real programs are more complicated and usually have a somewhat different organization l More about this later, after the mechanics of exception handling, their definition and use have been explained

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 4 Some terminology l Throwing an exception: either Java itself or your code signals when something unusual happens l Handling an exception: responding to an exception by executing a part of the program specifically written for the exception »also called catching an exception The normal case is handled in a try block The exceptional case is handled in a catch block The catch block takes a parameter of type Exception »it is called the catch -block parameter »e is a commonly used name for it If an exception is thrown execution in the try block ends and control passes to the catch block(s) after the try block

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 5 try-throw-catch threesome l Basic code organization: try { if(test condition) throw new Exception("Message to display"); } catch(Exception e) { }

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 6 try-throw-catch program flow Try block Statements execute up to the conditional throw statement If the condition is true the exception is thrown »control passes to the catch block(s) after the try block Else the condition is false »the exception is not thrown »the remaining statements in the try block (those following the conditional throw) are executed Catch block Executes if an exception is thrown »may terminate execution with exit statement »if it does not exit, execution resumes after the catch block Statements after the Catch block Executes if either the exception is not thrown or if it is thrown but the catch block does not exit

An example of exception handling Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 7 ExceptionDemo try and catch blocks (from Display 8.2/page 407) try block throw statement catch block

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 8 More about the catch block l Although it may look similar to a method definition The catch block is not a method definition! Every Exception has a getMessage method »it retrieves the string given to the exception object when it was thrown, e.g. throw new Exception("This message is retrieved"); A catch block applies only to an immediately preceding try block »if no exception is thrown the catch block is ignored

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Predefined exception classes Exception is the root class of all exceptions l Many predefined classes throw exceptions »the documentation or interface will tell you »the exceptions thrown are often also predefined l Some common predefined exceptions: »IOException »ClassNotFoundException, and »FileNotFoundException

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Code organization when using an object that may throw an exception Sample object = new SampleClass(); try { object.doStuff;//may throw IOException } catch(IOException e) { System.out.println(e.getMessage()); } Predefined exceptions usually include a meaningful message that is retrieved with getMessage

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Defining your own exception classes l Must be derived from some already defined exception class l Often the only method you need to define is the constructor Include a constructor that takes a String message argument Also include a default constructor with a call to super and default message string For example Display 8.3/page 417

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 12 Example: using the DivideByZeroException class Excerpt from DivideByZeroExceptionDemo (Display 8.4/page 418):

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 13 Catching an exception in a method other than the one that throws it When defining a method you must include a throws -clause to declare any exception that might be thrown but is not caught in the method. Use a throws -clause to "pass the buck" to whatever method calls it (pass the responsibility for the catch block to the method that calls it) »that method can also pass the buck, but eventually some method must catch it l This tells methods other methods "If you call me, you must handle any exceptions that I throw."

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 14 Example: throws -clause DoDivision, Display 8.5/page 424 It may throw a DivideByZeroException in the method normal But the catch block is in main So normal must include a throws -clause in the first line of the constructor definition: public void normal() throws DivideByZeroException { }

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 15 More about passing the buck Good programming practice: Every exception thrown should eventually be caught in some method Normally exceptions are either caught in a catch block or deferred to the calling method in a throws -clause If a method throws an exception, it expects the catch block to be in that method unless it is deferred by a throws -clause »if the calling method also defers with a throws -clause, its calling program is expected to have the catch block, etc., up the line all the way to main, until a catch block is found

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Uncaught exceptions l In any one method you can catch some exceptions and defer others l If an exception is not caught in the method that throws it or any of its calling methods, either: »the program ends, or, »in the case of a GUI using the AWT, the program may become unstable "Exceptions" derived from the classes Error and RunTimeError do not need a catch block or throws -clause »they look like exceptions, but they are not descendents of Exception

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 17 throws -clauses in derived classes You cannot add exceptions to the throws -clause of a redefined method in a derived class »only exceptions in the throws -clause of the parent class's method can be in the throws -clause of the redefined method in the derived class In other words, you cannot throw any exceptions that are not either caught in a catch block or already listed in the throws - clause of the same method in the base class You can, however, declare fewer exceptions in the throws - clause of the redefined method

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Multiple exceptions and catch blocks in a method l Methods can throw more than one exception The catch blocks immediately following the try block are searched in sequence for one that catches the exception type »the first catch block that handles the exception type is the only one that executes l Specific exceptions are derived from more general types »both the specific and general types from which they are derived will handle exceptions of the more specific type So put the catch blocks for the more specific, derived, exceptions early and the more general ones later

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 19 Warning revisited: l As stated earlier, the example programs in this chapter are simplified for instructional purposes »catch blocks are sometimes defined either in the method that throws the exception l Real programs are more complicated and usually have a somewhat different organization »catch blocks are usually defined in a different method

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Typical program organization for exception handling in real programs MethodA throws MyException but defers catching it (by using a throws -clause: MethodB, which calls MethodA, catches MyException exceptions:

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 21 Exception: reality check l Exception handling can be overdone »use it sparingly and only in certain ways l If the way an exceptional condition is handled depends on how and where the method is invoked, then it is better to use exception handling and let the programmer handle the exception (by writing the catch block and choosing where to put it) l Otherwise it is better to avoid throwing exceptions l An example of this technique is shown in the case study A Line- Oriented Calculator (starting on page 437)

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 22 The finally block At this stage of your programming you may not have much use for the finally block, but it is included for completeness - you may have find it useful later You can add a finally block after the try / catch blocks finally blocks execute whether or not catch block(s) execute Code organization using finally block: try block catch block finally { }

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 23 Summary... An exception is an object descended from the Exception class Descendents of the Error class act like exceptions but are not l Exception handling allows you to design code for the normal case separately from that for the exceptional case l You can use predefined exception classes or define your own l Exceptions can be thrown by: »certain Java statements »methods from class libraries »explicit use of the throw statement l An exception can be thrown in either »a try block, or »a method definition without a try block, but in this case the call to the method must be placed inside a try block

Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch summary, continued l An exception is caught in a catch block When a method might throw an exception but does not have a catch block to catch it, usually the exception class must be listed in the throws -clause for the method l A try block may be followed by more than one catch block »more than one catch block may be capable of handling the exception »the first catch block that can handle the exception is the only one that executes »so put the most specific catch blocks first and the most general last Every exception class has a getMessage method to retrieve a text message description of the exception caught l Do not overuse exceptions