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:



Advertisements
Similar presentations
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Advertisements

Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Comp 249 Programming Methodology
1 Week 11 l Basic Exception Handling »the mechanics of exceptions l Defining and Using Exceptions »some "simple" cases l Reality Check »guidelines for.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
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,
CSIS 123A Lecture 11 Exception Handling. Introduction  Typical approach to development:  Write programs assuming things go as planned  Get ‘core’ working.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exception Handling By: Thomas Fasciano. What is an Exception?  An error condition that occurs during the execution of a Java Program.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
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.
Exception Handling. Introduction One benefit of C++ over C is its exception handling system. An exception is a situation in which a program has an unexpected.
Chapter 9 Exception Handling Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 9 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.
CS102--Object Oriented Programming Lecture 11: Exception Handling Copyright © 2008 Xiaoyan Li.
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.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch Announcements l Project 6 now out. »Milestone due Oct. 24th »Final project.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Exception Handling (Chapter 8) CS 180 Recitation - February 29, 2008 Department of Computer Science Purdue University.
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
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Object Oriented Programming
CIS 270—Application Development II Chapter 13—Exception Handling.
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.
Java Programming: Guided Learning with Early Objects
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
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 
Chapter 8-Exception Handling/ Robust Programming.
Lecturer: Dr. AJ Bieszczad Chapter 8 COMP 150: Introduction to Object-Oriented Programming 8-1 l Basic Exception Handling »the mechanics of exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
Chapter 16 Exception Handling
Chapter 9 Exception Handling
Chapter 14: Exception Handling
Announcements/Reminders
Exception Handling Chapter 9.
Exception Handling Chapter 8 Basic Exception Handling
Exceptions & exception handling
Exceptions & exception handling
Exception Handling Chapter 9 Edited by JJ.
COS 260 DAY 20 Tony Gauvin.
Exception and Event Handling
Exception Handling Chapter 8 Basic Exception Handling
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Presentation transcript:

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 twice a week (7-9 pm: M in CS G066, W in Phys 11)

Chapter 83 Exam 2 Tuesday, October 25 7:00 – 8:00 PM Physics 112 Covers chapters 5-9 (and material from 1-4 as well) Same format as exam 1 –20 MC –5 programming

Chapter 84 Introduction A program can be written assuming that nothing unusual or incorrect will happen. –The user will always enter an integer when prompted to do so. –There will always be a nonempty list for a program that takes an entry from the list. –The file containing the needed information will always exist. Unfortunately, it isn’t always so.

Chapter 85 Exception Handling Either your code or Java signals when something unusual happens. The signaling process is called throwing an exception. Somewhere in your program, you can place code to handle the exception.

Chapter 86 Exceptions in Java: Example, cont. simple example, cont. –But what if there is no milk? –An attempt to divide the number of donuts by the number of glasses of milk will result in an attempt to divide by zero. –This would be an utter (udder?) disaster, known in Java as an exception.

Chapter 87 Exceptions in Java: Example, cont. In Java, it is possible to test for this unusual situation using an if-else statement, for example.

Chapter 88

9 Exceptions in Java: Example, cont.

Chapter 810 Exceptions in Java: Example, cont. In Java, it is also possible to throw an exception.

Chapter 811

Chapter 812 Exceptions in Java: Example, cont.

Chapter 813 Defining Exception Classes You can define your own exception classes, but they must be derived from an existing exception class. Constructors are the most important, and often the only methods (except for methods inherited from the base class).

Chapter 814 Defining Exception Classes, cont. class DivideByZeroException

Chapter 815

Chapter 816 Java Tip: Preserve getMessage For all predefined exception classes, method getMessage returns either –the string that is passed as an argument to the constructor or –a default string if no argument is passed to the constructor. The behavior of method getMessage should be preserved in any exception class you define.

Chapter 817 Java Tip: Preserve getMessage, cont. This is done by including a string parameter that begins with a call to super. public MyException(String message) { super(message); More_Code_If_Appropriate }

Chapter 818 Java Tip: Preserve getMessage, cont. Also include a default constructor. public MyException() { super(“MyException thrown”); More_Code_If_Appropriate }

Chapter 819 Programming Tip: When to Define an Exception Class In general, define an exception class if you are going to insert a throw statement in your code. This permits catch blocks to distinguish between your exceptions and exceptions thrown by predefined methods.

Chapter 820 Guidelines Use class Exception as the base class unless there is a compelling reason to do otherwise. Define at least two constructors. Typically, no other methods are needed. Begin each constructor definition with a call to the constructor of the base class.

Chapter 821 Declaring Exceptions (Passing the Buck) Sometimes is it appropriate to handle an exception other than in the method where the exception occurred. For example, it might be better to handle the exception in the method that called the method that called the method… that threw the exception

Chapter 822 Declaring Exceptions, cont. If a method can throw an exception but does not catch it, it must alert the programmer to the possibility of an exception by including a throws clause. Example public void someMethod() throws DivideByZeroException

Chapter 823 Accounting for Exceptions An exception can be caught in a catch block within a method definition. Alternatively, the possibility of an exception can be declared at the start of the method definition by placing the exception-class name in a throws clause. These two approaches can be mixed in a method, catching some exceptions and declaring others in a throws clause.

Chapter 824 Accounting for Exceptions, cont. If method_A uses a throws clause instead of handling an exception and method_B calls method_A, then method_B either must handle the exception or must also include a throws clause.

Chapter 825

Chapter 826 Accounting for Exceptions, cont. A throws clause can include more than one exception type. example public int someMethod()throws IOException, DivideByZeroException

Chapter 827 Accounting for Exceptions, cont. Some method in the calling hierarchy should handle the exception. If an exception is thrown, but never caught, either the program terminates or its behavior becomes unreliable.

Chapter 828 Exceptions That Need Not Be Caught Some exceptions do not need to be accounted for in any way. –(Perhaps these are the exceptions that prove the rule about needing to account for exceptions.) Exceptions that do not need to be accounted for result from errors and usually are thrown by methods in predefined classes.

Chapter 829 throws Clauses in Derived Classes When a method is redefined in a derived class, the redefined method cannot contain any exception classes that are not in the throws clause of the same method in the base class (though the derived class can list fewer exceptions in its throws clause). Any exceptions thrown in the derived class must be caught or thrown by the base class.

Chapter 830 Multiple Throws and Catches A try block can throw any number of different types of exceptions. Each catch block can catch only one type of exception. Multiple catch blocks after a try block can catch multiple types of exceptions.

Chapter 831

Chapter 832 Java Tip: Catch the More Specific Exceptions First catch blocks are examined in order. The first matching catch block is executed. More specific exceptions should precede less specific exceptions, i.e. exceptions lower in the exception hierarchy should come before exceptions higher in the exception hierarchy.

Chapter 833 Keep It Simple Attempt to modify a program or class definition so that it does not need a throw statement. In general, use exceptions sparingly. If the way the exception is handled depends on the calling method, let the calling method handle the exception. Consider throwing the exception and catching the exception in separate methods.

Chapter 834 Keep It Simple, cont. public void methodB() {... try {... methodA();... } catch (MyException e)...

Chapter 835 The finally Block A finally block can be added after a try block and its catch blocks. The finally block is executed –if the try block throws no exceptions –if the try block throws an exception which is caught by a catch block –if an exception is thrown but not caught i.e. it is always executed.

Chapter 836 The finally Block, cont. syntax try { … } catch Block(s) finally { … }

Chapter 837 try { doMethod(“test”); } catch (Exception e) { System.out.println(“Exception”); return; } finally { System.out.println(“Done”); } return; If doMethod() throws an exception, what is the output?

Chapter 838 Output Exception Done

Chapter 839 Output Exception Done why?

Chapter 840 Graphics Supplement: Exceptions in GUIs An uncaught exception in a (non-GUI) application will end the program. An uncaught exception in a GUI program (either a JFrame GUI or an applet) will not end the program. –However, unless the exception is caught, the GUI may not cope correctly with the exception or the user may receive insufficient instructions.

Chapter 841 Programming Example: A JFrame Using Exceptions The example JFrame GUI allows the user to write the name of a color in a text field and to click the “Show Color” button. –If the GUI recognizes the color, the background color changes to the named color. –Otherwise, the text field displays “Unknown Color” and the background changes to gray.

Chapter 842 Programming Example: A JFrame Using Exceptions, cont. class ColorDemo

Chapter 843 class UnknownColorException Programming Example: A JFrame Using Exceptions, cont.

Chapter 844 class ShowColorDemo Programming Example: A JFrame Using Exceptions, cont.

Chapter 845 Programming Example: A JFrame Using Exceptions, cont.

Chapter 846 throws Clause Not Allowed in actionPerformed A throws clause cannot be added to method actionPerformed in any action listener class. Any exception thrown in method actionPerformed must be caught in method actionPerformed. Similarly, if method windowClosing is redefined in a window listener class, you may not add a throws clause to method windowClosing.

Chapter 847 Summary You have become familiar with the notion of exception handling. You have learned Java syntax for exception handling. You have learned to use exception handling effectively in classes and programs.