Exception Handling 1 CISC6795, Spring 2011. Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:

Slides:



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

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.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 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.
 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.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
 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 Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
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.
Pemrograman VisualMinggu …12… Page 1 MINGGU Ke Duabelas Pemrograman Visual Pokok Bahasan: Exception Handling Tujuan Instruksional Khusus: Mahasiswa dapat.
Slides Credit Umair Javed LUMS Web Application Development.
Java Programming: Guided Learning with Early Objects
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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 –
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.
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.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
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.
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.
Appendix H Exception Handling: A Deeper Look
Exception Handling in C++
16 Exception Handling.
Exception Handling and Format output-CS1050-By Gayani Gupta
13 Exception Handling.
Chapter 14: Exception Handling
Web Design & Development Lecture 7
Exception Handling.
Chapter 15 – Exception Handling
Presentation transcript:

Exception Handling 1 CISC6795, Spring 2011

Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples: ArrayIndexOutOfBoundsException – an attempt is made to access an element past end of an array ClassCastException – an attempt is made to cast an object that does not have an is-a relationship with type specified in cast operator ArithmeticException – can arise from a number of different problems in arithmetic InputMismatchException – occurs when Scanner method nextInt receives a string that does not represent a valid integer Exception handling – resolving exceptions that may occur so program can continue or terminate gracefully

3 Attempt to divide; denominator may be zero Read input; exception occurs if input is not a valid integer

Outline 4

Exception-Handling Overview 5 Traditional way to handle various error condition: Check for error condition returned by return value, and process it Intermixing program logic with error-handling logic can make programs difficult to read, modify, maintain and debug If potential problems occur infrequently, degrade a program’s performance

Exception-Handling Overview 6 Exception handling enables programmers to remove error- handling code from the “main line” of program’s execution Improves clarity Enhances modifiability Language mechanisms: Extensible exception hierarchy (exception is a class) throw exceptions: to generate an exception object to indicate an error condition try block: to enclose codes that might throw exceptions catch block: to handle exception

try statement 7 try statement : one try block and corresponding catch and/or finally blocks Possible multiple catch blocks, each catching a particular type of exception NO code between a try block and its corresponding catch blocks. Cannot catch same type of exception in two different catch blocks Uncaught exception – an exception that occurs for which there are no matching catch blocks

Outline 8 throws clause specifies that method quotient may throw an ArithmeticException try block attempts to read input and perform division

9 Call method quotient, which may throw ArithmeticException Exception parameters Standard streams: System.out – standard output stream, System.err – standard error stream Both by default are linked to command terminal print,println, printf methods

Enclosing Code in a try Block 10 try block –keyword try followed by a block of code encloses code that might throw an exception and subsequent code that should not execute if exception occurs E.g., if open file calls fails, should not continue to read file … E.g., if reading from standard input failed, should not process input… Throw point of an exception: the statement that leads to the exception, it can be A throw statement calls to other method that throw an exception deeply nested method calls initiated by code in a try block from Java Virtual Machine as it executes Java bytecodes. Do not place try... Catch… finally... around every statement that may throw an exception.

Catch block 11 catch block – catches and handles an exception catch (ArithmeticException exception) { } keyword catch, followed by exception parameter in parentheses – which identifies exception type and name, Each catch block can have only a single parameter followed by block of code in curly braces that executes when exception of specified type occurs Display the caught exceptions Prompt user to try again, or clean up before terminating program

finally block 12 finally block, optional in the try statement finally keyword followed by a block of code Executes whether or not an exception is thrown in try block or any of its corresponding catch blocks Will not execute if application exits early from a try block via method System.exit Typically contains resource-release code to avoid resource leaks E.g., finally block should close any files opened in try block.

Program control in Exception Handling 13 Execute statements in try block If no exception occurs: Skip catch blocks to finally block. After executing finally block, control proceeds to first statement after finally block. If an exception occurs: Skips rest of try block. First matching catch block executes If no matching catch blocks, control proceeds to finally block, and then passes exception to next outer try block If catch block throws an exception, finally block still executes finally block executes. Control proceeds to first statement after finally block

Outline 14 throws clause specifies that method quotient may throw an ArithmeticException try block attempts to read input and perform division

15 Call method quotient, which may throw ArithmeticException Exception parameters

16

Exception Inheritance Hierarchy 17 Exception classes form an extensible inheritance hierarchy Throwable objects can be used with exception mechanism Subclass Error : abnormal situations happen in JVM –usually impossible for a program to recover from Error s Subclass Exception : exception situations that can occur and be caught in a Java program

Java Exception Hierarchy 18 catch block catches all exceptions of its type and subclasses of its type An subclass exception object is a superclass exception object If there are multiple catch blocks that match a particular exception type, only first matching catch block executes Define a catch block for a superclass when all catch blocks for that class’s subclasses perform same functionality This guarantees that exceptions of all subclasses will be caught. If some subclass exceptions need special handling, position their catch blocks before the catch block for superclass type Placing them in opposite order prevents subclass catch blocks from executing, so a compilation error occurs.

Checked and Unchecked Exceptions 19 Checked exception, inherit from Exception but not from RuntimeException Unchecked exception: inherit from Error or untimeException

Checked and Unchecked Exceptions 20 Checked exception, inherit from Exception but not from RuntimeException Compiler enforces a catch-or-declare requirement, i.e., someone must handle it For each method call: If the method declaration suggests that it throws some checked exceptions, compiler ensures that the checked exception is caught or is declared in a throws clause. Unchecked exception: compiler does not check whether such exception is caught or declared If it occurs and is not caught, program terminates or runs with unexpected results Handling them makes program more robust, e.g., NumberFormatException, a subclass of RuntimeException

throws Clause in method head 21 throws clause – specifies exceptions a method may throws after method’s parameter list and before method’s body a comma-separated list of exceptions Exceptions can be thrown by statements in method’s body of by methods called in method’s body Exceptions can be of types listed in throws clause or subclasses If a method explicitly throws a checked exception, or calls another method that throws one, it must list the exception in the throw clause, or catch it If an exception can be handled meaningfully in a method, the method should catch it rather than declare it.

Throwing Exceptions 22 You can thrown exceptions from a method if something has gone wrong throw statement: throw followed by an exception object Example: Exceptions can be thrown from constructors. When an error is detected in a constructor, an exception should be thrown rather than creating an improperly formed object. Exceptions are rethrown when a catch block decides either that it cannot process the exception or that it can only partially process it Exception is deferred to outer try statement Exception is rethrown by using keyword throw followed by a reference to the exception object

Examples about throwing/handling exception 23

24 Call method that throws an exception

25 Create new Exception and throw itThrow previously created Exceptionfinally block executes even though exception is rethrown in catch block

26 finally block executes even though no exception is thrown

Stack Unwinding 27 Stack unwinding – when an exception is thrown but not caught, method-call stack is “unwound,” and an attempt is made to catch the exception in the next outer try block. The method in which exception was not caught terminates All local variables in that method go out of scope Control returns to the statement that originally invoked the method – if a try block encloses the method call, an attempt is made to catch the exception.

Outline 28 Call method that throws an exception Catch exception that may occur in the above try block, including the call to method throwException

Outline 29 Method throws exception Throw new exception; Exception not caught in current try block, so handled in outer try block finally block executes before control returns to outer try block

printStackTrace, getStackTrace and getMessage 30 class Throwable provides method to retrieve info. about an exception getMessage – returns the descriptive string stored in an exception printStackTrace – outputs stack trace to standard error stream getStackTrace – retrieves stack trace information as an array of StackTraceElement objects; enables custom processing of the exception information

Exercises 31 Modify previous program to print out info. about Exception what if we do not catch exception in main ? An exception that is not caught in an application causes Java’s default exception handler to run. This displays the name of the exception, a descriptive message that indicates the problem that occurred and a complete execution stack trace. Never ignore an exception you catch. At least use printStackTrace to output an error message. This will inform users that a problem exists, so that they can take appropriate actions.

printStackTrace, getStackTrace and getMessage 32 StackTraceElement methods getClassName getFileName getLineNumber getMethodName Stack trace information follows pattern – className.methodName(fileName:lineNumber)

33 Display stack trace for exception thrown in method3 Retrieve stack information as an array of StackTraceElement objects

Outline 34

Outline 35 Exception created and thrown

Chained Exceptions 36 Chained exceptions enable an exception object to maintain the complete stack-trace information when an exception is thrown from a catch block Users can retrieve information about original exception Stack trace from a chained exception displays how many chained exceptions remain

Outline 37 Catch exception from method1 as well as any associated chained exceptions

Outline 38 Catch exception from method2, throw new exception to be chained with earlier exceptions Catch exception from method3, throw new exception to be chained with earlier exceptions

Outline 39 Original thrown exception

Error-Prevention Tip 40 Read online API documentation for a method before using that method in a program. The documentation specifies the exceptions thrown by the method (if any) and indicates reasons why such exceptions may occur. Then provide for handling those exceptions in your program. If you know that a method might throw an exception, include appropriate exception-handling code in your program to make it more robust.

Define new exception class 41

Declaring New Exception Types 42 You can declare your own exception classes that are specific to the problems that can occur when another program uses your reusable classes By convention, all exception-class names should end with word Exception. New exception class must extend an existing exception class Typically contains only two constructors One takes no arguments, passes a default exception messages to the superclass constructor One that receives a customized exception message as a string and passes it to the superclass constructor If possible, indicate exceptions from your methods by using existing exception classes, rather than creating new exception classes. The Java API contains many exception classes that might be suitable for the type of problem your method needs to indicate.

Checked or unchecked exception? 43 a checked exception (i.e., extend Exception but not RuntimeException ) if clients should be required to handle the exception. The client application should be able to reasonably recover from such an exception. extend RuntimeException if the client code should be able to ignore the exception (i.e., an unchecked exception).