Exception Handling 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.

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

Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
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.
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
Index Exception handling Exception In Java Exception Types
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
 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.
Error Handling with Exceptions Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
C++ Exception Handling
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Exception Handling. Definition  The term exception is shorthand for the phrase "exceptional event.“  An exception is an event, which occurs during the.
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
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
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 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
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.
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.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
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.
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.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exceptions in the Java programming language J. W. Rider.
Appendix H Exception Handling: A Deeper Look
13 Exception Handling.
Chapter 14: Exception Handling
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Java Basics Exception Handling.
Chapter 11 Exception Handling: A Deeper Look
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Exception Handling 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang

2

Introduction Exception — an indication of a problem that occurs during a program’s execution. – The name “exception” implies that the problem occurs infrequently. nition.html: nition.html − " The term exception is shorthand for the phrase exceptional event.“ − Definition: An exception is an event, which occurs during the execution of a program and disrupts the normal flow of the program's instructions. With exception handling, a program can continue executing (rather than terminating) after dealing with the exception. – Mission-critical or business-critical computing. – Robust and fault-tolerant programs (i.e., programs that can deal with problems as they arise and continue executing).

4 A review of what we saw before …

5

6 The client application Fig. 8.2 (TimeTest.java)

7

8 Questions regarding exception handling in the sample application: Q1: Which method in which class would throw the IllegalArgumentException? Q2: Under what condition would the exception be thrown? Q3: How would the client catch the exception when it is thrown?

9 Method setTime() and Exception Handling For incorrect values, setTime throws an exception of type IllegalArgumentException (lines 23–24) Notifies the client code that an invalid argument was passed to the method. Q: Who’s the client of setTime() in this application? The throw statement (line 23) creates a new object of type IllegalArgumentException. In this case, we call the constructor that allows us to specify a custom error message. After the exception object is created, the throw statement immediately terminates method setTime() and the exception is returned to the client code that attempted to set the time. The client can use try... catch to catch exceptions and attempt to recover from them.

10 Some sample exceptions we’ve seen … ArrayIndexOutOfBoundsException occurs when an attempt is made to access an element past either end of an array. A NullPointerException occurs when a null reference is used where an object is expected. ClassCastException occurs when an attempt is made to cast an object that does not have an is-a relationship with the type specified in the cast operator. ClassNotFoundException, IOException, … For a list of subclasses of Exception, see

11 The Throwable class is the superclass of all errors and exceptions in the Java language. − An Error indicates serious problems that a reasonable application should not try to catch. ( − The class Exception and its subclasses indicates conditions that a reasonable application might want to catch. ( Only objects that are instances of Throwable (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only Throwable or one of its subclasses can be the argument type in a catch clause. The Throwable class

12 Exceptions are thrown (i.e., the exception occurs) when a method detects a problem and is unable to handle it. Stack trace — information displayed when an exception occurs and is not handled. Information includes: – The name of the exception in a descriptive message that indicates the problem that occurred – The method-call stack (i.e., the call chain) at the time it occurred. Represents the path of execution that led to the exception method by method. Exception Handling and the Call Stack

The Call Stack 13 Source: main( )  m1( )  m2( )  m3( )

The Catch or Specify Requirement (aka. Catch or Declare) From: Valid Java code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following: a)A try statement that catches the exception. The try must provide a handler for the exception. e.g., m1( ) b)A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception. e.g., m3( ) 14

15

16

Example: Handling ArithmeticException s and InputMismatchExceptions The application in Fig uses exception handling to process any ArithmeticException s and InputMistmatchException s that arise. If the user makes a mistake, the program catches and handles the exception — in this case, allowing the user to try to enter the input again.

18

19

20 Q: What code should be enclosed within the try block? – code that might throw an exception – code that should not execute if an exception occurs The catch block (also called a catch clause or exception handler) catches and handles an exception. – Begins with the keyword catch and is followed by an exception parameter in parentheses and a block of code enclosed in curly braces. At least one catch block or a finally block (Section 11.6) must immediately follow the try block.

21 The exception parameter in the catch block identifies the exception type the handler can process. – The parameter’s name enables the catch block to interact with a caught exception object. When an exception occurs in a try block, the catch block that executes is the first one whose type matches the type of the exception that occurred. Use the System.err (standard error stream) object to output error messages. – By default, displays data to the command prompt. – Can be redirected to a log file for persistent data storage.

22 If an exception occurs in a try block, the try block terminates immediately and program control transfers to the first matching catch block. If there are remaining statements after the statement that causes the exception, those remaining statements won’t be executed. After the exception is handled, control resumes after the last catch block. Known as the termination model of exception handling. c.f., Some languages (not Java) use the resumption model of exception handling, in which, after an exception is handled, control resumes just after the throw point.

23 If no exceptions are thrown in a try block, the catch blocks are skipped and control continues with the first statement after the catch blocks – But, the finally block, if one is present, will execute whether or not an exception is thrown in the corresponding try block. (more about the finally block in Section 11.6) The try block and its corresponding catch and/or finally blocks form a try statement.

24 When a try block terminates, local variables declared in the block go out of scope. – The local variables of a try block are not accessible in the corresponding catch blocks. When a catch block terminates, local variables declared within the catch block (including the exception parameter) also go out of scope. Any remaining catch blocks in the try statement are ignored, and execution resumes at the first line of code after the try … catch sequence. – Or a finally block, if one is present.

25 The throws clause – Specifies the exceptions a method may throw. – Appears after the method’s parameter list and before the method’s body. – Contains a comma-separated list of the exceptions that the method will throw if various problems occur. May be thrown by statements in the method’s body or by methods called from the body. – Method can throw exceptions listed in its throws clause or their subclasses. e.g., NullPointerException is a subclass of RuntimeException. See exception hierarchy in – Clients of a method with a throws clause are thus informed that the method may throw exceptions.

26 Exercise: Try the recommended procedure using the read( ) method in FileInputStream. How would you handle exception(s) that might be thrown by the read( ) method.

27

Java Exception Hierarchy Exception classes inherit directly or indirectly from class Exception, forming an inheritance hierarchy. – Can extend this hierarchy with your own exception classes. Figure 11.3 shows a small portion of the inheritance hierarchy for class Throwable (a subclass of Object ), which is the superclass of class Exception. – Only Throwable objects can be used with the exception-handling mechanism. Class Throwable has two subclasses: Exception and Error.

29

The chained exception Source: A Throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Finally, it can contain a cause: another Throwable that caused this Throwable to get thrown. The cause facility is also known as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a "chain" of exceptions, each caused by another. 30

31 An exception’s type determines whether it is checked or unchecked. Direct or indirect subclasses of class RuntimeException (package java.lang ) are unchecked exceptions. – Typically caused by defects in your program’s code (e.g., ArrayIndexOutOfBoundsException s). Subclasses of Exception but not RuntimeException are checked exceptions. – Caused by conditions that are not in the control of the program e.g., in file processing, the program can’t open a file because the file does not exist. Checked vs unchecked exceptions

32

33 Unchecked exceptions −The compiler does not check the code to determine whether an unchecked exception is caught or declared. −These typically can be prevented by proper coding. −For example, an ArithmeticException can be avoided if a method ensures that the denominator is not zero before attempting to perform the division. −Unchecked exceptions are not required to be listed in a method’s throws clause. −It’s not required that such exceptions be caught by the application.

34 Superclass/Subclass Exceptions −A catch parameter of an exception can also catch all of that exception type’s subclass types. −Enables catch to handle related errors with a concise notation −Allows for polymorphic processing of related exceptions −Catching related exceptions in one catch block makes sense only if the handling behavior is the same for all subclasses. −You can also catch each subclass type individually if those exceptions require different processing.

35 If multiple catch blocks match a particular exception type, only the first matching catch block executes. It’s a compilation error to catch the exact same type in two different catch blocks associated with a particular try block.

The finally Block Programs that obtain resources must return them to the system explicitly to avoid so-called resource leaks, causing system resources to be unavailable to the OS and other programs. – In programming languages such as C and C++, the most common kind of resource leak is a memory leak. – Malicious programs may perform memory scanning to retrieve sensitive data that are not protected in the computer’s memory. – Java automatically garbage collects memory no longer used by programs, thus avoiding most memory leaks. – Other types of resource leaks can occur. Files, database connections and network connections that are not closed properly might not be available for use in other programs. The finally block is used for resource deallocation. – Placed after the last catch block.

37

38 The finally block will execute whether or not an exception is thrown in the corresponding try block. The finally block will execute if a try block exits by using a return, break or continue statement or simply by reaching its closing right brace. The finally block will not execute if the application terminates immediately by calling method System.exit().

39 If an exception that occurs in a try block cannot be caught by one of that try block’s catch handlers, control proceeds to the finally block. Then the program passes the exception to the next outer try block—normally in the calling method—where an associated catch block might catch it. – This process can occur through many levels of try blocks. – The exception could go uncaught. If a catch block throws an exception, the finally block still executes. – Then the exception is passed to the next outer try block—again, normally in the calling method.

40 Fig. 11.4: Testing exception handling and the finally clause

41

42

43

44

Stack Unwinding and Obtaining Information from an Exception Object 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.

46 Fig. 11.5: Demonstration of stack unwinding in handling exceptions Exercise: Draw the stack of method calls that would result from the method calls in the sample program. Exercise: If you want to make method2( ) catch the exception (and print the stack trace of that exception), how would you revise the code?

47

48

49

50

Declaring New Exception Types 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.

52

53 More resources: To find examples and more information about defining your own exception classes, check out the following: Lesson: Exceptions, The Java Tutorials: Excellent step-by-step tutorial about exceptions. Using your own exception classes in Java: Advanced; involving the use of Java Servlets and SQL database server.

54 Advantages of Exception Handling in Java ( 1.Separating Error-Handling Code from "Regular" Code In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code, with special values representing various errors. 2.Propagating Errors Up the Call Stack Easy tracing of the location where errors occur. 3.Grouping and Differentiating Error Types The hierarchy of Throwable