 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Topics Introduction Types of Errors Exceptions Exception Handling
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
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.
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.
 2006 Pearson Education, Inc. All rights reserved. Exception Handling in C++ CS-2303, C-Term Exception Handling in C++ CS-2303 System Programming.
Exception Handling and Format output
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.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
 Pearson Education, Inc. All rights reserved Exception Handling.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
C++ Exception Handling
Exception Handling 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 15 Strings String::Concat String::CompareTo, Equals, == If( string1 == S”Hello”) String1->Equals(S”Hello”) String1->CompareTo(S”Hello”) CompareTo.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 10 Classes Continued
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Java Programming: Guided Learning with Early Objects
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Introduction to Exception Handling and Defensive Programming.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
FIRST JAVA PROGRAM. JAVA PROGRAMS Every program may consist of 1 or more classes. Syntax of a class: Each class can contain 1 or more methods. public.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
Appendix H Exception Handling: A Deeper Look
Exception Handling in C++
16 Exception Handling.
13 Exception Handling.
Chapter 14: Exception Handling
Chapter 11 Exception Handling: A Deeper Look
Presentation transcript:

 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard error stream) displays errors  Output from these streams can be redirected (e.g., to a file).  Using two different streams enables you to easily separate error messages from other output.  Data output from System.err could be sent to a log file  Data output from System.out can be displayed on the screen © Copyright by Pearson Education, Inc. All Rights Reserved.

 throw statement—indicates that an exception has occurred.  Used to throw exceptions.  Indicates to client code that an error has occurred.  Specifies an object to be thrown.  The operand of a throw can be of any class derived from class Throwable. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Rethrow an exception  Done when a catch block, cannot process that exception or can only partially process it.  Defers the exception handling (or perhaps a portion of it) to another catch block associated with an outer try statement.  Rethrow by using the throw keyword, followed by a reference to the exception object that was just caught.  When a rethrow occurs, the next enclosing try block detects the exception, and that try block’s catch blocks attempt to handle it. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Stack unwinding—When an exception is thrown but not caught in a particular scope, the method-call stack is “unwound”  An attempt is made to catch the exception in the next outer try block.  All local variables in the unwound method go out of scope and control returns to the statement that originally invoked that method.  If a try block encloses that statement, an attempt is made to catch the exception.  If a try block does not enclose that statement or if the exception is not caught, stack unwinding occurs again. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Sometimes a method responds to an exception by throwing a different exception type that is specific to the current application.  If a catch block throws a new exception, the original exception’s information and stack trace are lost.  Earlier Java versions provided no mechanism to wrap the original exception information with the new exception’s information.  This made debugging such problems particularly difficult.  Chained exceptions enable an exception object to maintain the complete stack-trace information from the original exception. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Sometimes it’s useful to declare your own exception classes that are specific to the problems that can occur when another programmer uses your reusable classes.  A new exception class must extend an existing exception class to ensure that the class can be used with the exception-handling mechanism. © Copyright by Pearson Education, Inc. All Rights Reserved.

 A typical new exception class contains only four constructors:  one that takes no arguments and passes a default error message String to the superclass constructor;  one that receives a customized error message as a String and passes it to the superclass constructor;  one that receives a customized error message as a String and a Throwable (for chaining exceptions) and passes both to the superclass constructor;  and one that receives a Throwable (for chaining exceptions) and passes it to the superclass constructor. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Programmers spend significant amounts of time maintaining and debugging code.  To facilitate these tasks and to improve the overall design, they can specify the expected states before and after a method’s execution.  These states are called preconditions and postconditions, respectively. © Copyright by Pearson Education, Inc. All Rights Reserved.

 A precondition must be true when a method is invoked.  Describes constraints on method parameters and any other expectations the method has about the current state of a program just before it begins executing.  If the preconditions are not met, the method’s behavior is undefined.  You should never expect consistent behavior if the preconditions are not satisfied. © Copyright by Pearson Education, Inc. All Rights Reserved.

 A postcondition is true after the method successfully returns.  Describes constraints on the return value and any other side effects the method may have.  When calling a method, you may assume that a method fulfills all of its postconditions.  If writing your own method, document all postconditions so that others know what to expect when they call your method, and you should make certain that your method honors all its postconditions if its preconditions are met.  When preconditions or postconditions are not met, methods typically throw exceptions. © Copyright by Pearson Education, Inc. All Rights Reserved.

 As an example, examine String method charAt, which has one int parameter—an index in the String.  For a precondition, method charAt assumes that index is greater than or equal to zero and less than the length of the String.  If the precondition is met, the postcondition states that the method will return the character at the position in the String specified by the parameter index.  Otherwise, the method throws an Index-Out-Of-Bounds- Exception.  We trust that method charAt satisfies its postcondition, provided that we meet the precondition.  We need not be concerned with the details of how the method actually retrieves the character at the index. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Some programmers state preconditions and postconditions informally as part of the general method specification, while others prefer a more formal approach by explicitly defining them.  State the preconditions and postconditions in a comment before the method declaration.  Stating the preconditions and postconditions before writing a method will also help guide you as you implement the method. © Copyright by Pearson Education, Inc. All Rights Reserved.

 When implementing and debugging a class, it’s sometimes useful to state conditions that should be true at a particular point in a method.  Assertions help ensure a program’s validity by catching potential bugs and identifying possible logic errors during development.  Preconditions and postconditions are two types of assertions. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Java includes two versions of the assert statement for validating assertions programatically.  assert evaluates a boolean expression and, if false, throws an AssertionError (a subclass of Error ). assert expression ;  throws an AssertionError if expression is false. assert expression1 : expression2 ;  evaluates expression1 and throws an AssertionError with expression2 as the error message if expression1 is false.  Can be used to programmatically implement preconditions and postconditions or to verify any other intermediate states that help you ensure your code is working correctly. © Copyright by Pearson Education, Inc. All Rights Reserved.

 You use assertions primarily for debugging and identifying logic errors in an application.  You must explicitly enable assertions when executing a program  They reduce performance.  They are unnecessary for the program’s user.  To enable assertions, use the java command’s -ea command-line option, as in java -ea AssertTest © Copyright by Pearson Education, Inc. All Rights Reserved.

 Users should not encounter any AssertionError s through normal execution of a properly written program.  Such errors should only indicate bugs in the implementation.  As a result, you should never catch an AssertionError.  Allow the program to terminate when the error occurs, so you can see the error message, then locate and fix the source of the problem.  Since application users can choose not to enable assertions at runtime  You should not use assert to indicate runtime problems in production code.  You should use the exception mechanism for this purpose. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Common for a try block to be followed by several catch blocks to handle various types of exceptions.  If the bodies of several catch blocks are identical, you can use the new Java SE 7 multi- catch feature to catch those exception types in a single catch handler and perform the same task.  The syntax for a multi- catch header is:  catch ( Type1 | Type2 | Type3 e ) © Copyright by Pearson Education, Inc. All Rights Reserved.

 Each exception type is separated from the next with a vertical bar (|). The preceding line of code indicates that one of the specified types (or any subclasses of those types) can be caught in the exception handler. Any number of Throwable types can be specified in a multi- catch. © Copyright by Pearson Education, Inc. All Rights Reserved.

 Typically resource-release code should be placed in a finally block to ensure that a resource is released, regardless of whether there were exceptions when the resource was used in the corresponding try block.  An alternative notation—the try -with-resources statement (new in Java SE 7)—simplifies writing code in which you obtain one or more resources, use them in a try block and release them in a corresponding finally block. © Copyright by Pearson Education, Inc. All Rights Reserved.

 For example, a file-processing application (Chapter 17) could process a file with a try -with-resources statement to ensure that the file is closed properly when it’s no longer needed.  Each resource must be an object of a class that implements the AutoCloseable interface—such a class has a close method. © Copyright by Pearson Education, Inc. All Rights Reserved.

 The general form of a try -with-resources statement is try ( ClassName theObject = new ClassName() ) { // use theObject here } catch ( Exception e ) { // catch exceptions that occur while using the resource }  ClassName is a class that implements the AutoCloseable interface. © Copyright by Pearson Education, Inc. All Rights Reserved.

 This code creates an object of type ClassName and uses it in the try block, then calls its close method to release any resources used by the object.  The try -with-resources statement implicitly calls the Object’s close method at the end of the try block.  You can allocate multiple resources in the parentheses following try by separating them with a semicolon ( ; ). © Copyright by Pearson Education, Inc. All Rights Reserved.