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.

Slides:



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

Topics Introduction Types of Errors Exceptions Exception Handling
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
Exception Handling and Format output
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
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.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
©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.
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.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
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.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Slides Credit Umair Javed LUMS Web Application Development.
10-1 Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled.
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 --
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
COMP Exception Handling Yi Hong June 10, 2015.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
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)
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Chapter 10 Exceptions 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
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.
Appendix H Exception Handling: A Deeper Look
16 Exception Handling.
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Abdulmotaleb El Saddik University of Ottawa
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
Java Basics Exception Handling.
Presentation transcript:

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 and handled by another part of the program A program can be separated into a normal execution flow and an exception execution flow

Exceptions Exception an indication of a problem occurring during program’s execution The name “exception” implies that the problem occurs infrequently With exception handling, a program can continue executing (rather than terminating) after dealing with a problem. Robust and fault-tolerant programs (i.e., programs that can deal with problems as they arise and continue executing).

Examples of Exceptions ArrayIndexOutOfBoundsException occurs when an attempt is made to access an element past either end of an array. 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. NullPointerException occurs when a null reference is used where an object is expected.

Example: Divide by zero without Exception Handling 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. This information helps you debug the program.

Example: Divide by zero without Exception Handling (Cont.) Java does not allow division by zero in integer arithmetic. Throws an ArithmeticException. Can arise from a several problems, so an error message (e.g., “/ by zero”) provides more specific information. Java does allow division by zero with floating-point values. Such a calculation results in the value positive or negative infinity Floating-point value that displays as Infinity or -Infinity. If 0.0 is divided by 0.0, the result is NaN (not a number),  which is represented as a floating-point value that displays as NaN.

Example: Divide by zero without Exception Handling (Cont.) Last “at” line in the stack trace started the call chain. Each line contains the class name and method followed by the file name and line number. The top “at” line of the call chain indicates the throw point—the initial point at which the exception occurs. As you read a stack trace top to bottom, the first “at” line that contains your class name and method name is typically the point in the program that led to the exception.

Example: Divide by zero without Exception Handling (Cont.) Prior examples that read numeric values from the user assumed that the user would input a proper integer value. Users sometimes make mistakes and input noninteger values. An InputMismatchException occurs when Scanner method nextInt receives a String that does not represent a valid integer.

Exception handling

Exception Handling Java has a predefined set of exceptions that can occur during execution A program can deal with an exception in one of three ways: ignore it handle it where it occurs handle it an another place in the program The manner in which an exception is processed is an important design consideration

Exception Handling If an exception is ignored by the program, the program will terminate abnormally and produce an appropriate message The message includes a call stack trace that: indicates the line on which the exception occurred shows the method call trail that lead to the attempted execution of the offending line

The try-catch Statement To handle an exception in a program, the line throwing exception is executed within a try block A try block is followed by one or more catch clauses Each catch clause has an associated exception type and is called an exception handler When an exception occurs, processing continues at the first catch clause that matches the exception type

The finally Clause A try statement can have an optional clause following the catch clauses, designated by the reserved word finally The statements in finally are always executed If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete

Example: Divide by zero with Exception Handling This example uses exception handling to process any ArithmeticException and InputMistmatchException 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.

Example: Divide by zero with Exception Handling (Cont.) try block encloses code that might throw an exception code that should not execute if an exception occurs. Consists of the keyword try followed by a block of code enclosed in curly braces. catch block (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.

Example: Divide by zero with Exception Handling (Cont.) 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. If an exception occurs in a try block, the try block terminates immediately and program control transfers to the first matching catch block. After the exception is handled, control resumes after the last catch block.

Example: Divide by zero with Exception Handling (Cont.) 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 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

Exception Propagation

An exception can be handled at a higher level if it is not appropriate to handle it where it occurs Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method A try block that contains a call to a method in which an exception is thrown can be used to catch that exception

Exception class hierarchy

The Exception Class Hierarchy Classes that define exceptions are related by inheritance, forming an exception class hierarchy All error and exception classes are descendants of the Throwable class A programmer can define an exception by extending the Exception class or one of its descendants The parent class used depends on how the new exception will be used

The Exception Class Hierarchy Exception classes inherit directly or indirectly from class Exception, forming an inheritance hierarchy. Can extend this hierarchy with your own exception classes. Throwable 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.

The Exception Class Hierarchy Class Exception and its subclasses represent exceptional situations that can occur in a Java program These can be caught and handled by the application. Class Error and its subclasses represent abnormal situations that happen in the JVM. Errors happen infrequently. These should not be caught by applications. Applications usually cannot recover from Errors.

The Exception Class Hierarchy

Checked exceptions vs. unchecked exceptions. Compiler enforces a catch-or-declare requirement for checked exceptions. An exception’s type determines whether it is checked or unchecked. Direct or indirect subclasses of class RuntimeException are unchecked exceptions. Subclasses of Exception but not RuntimeException are checked exceptions.

The throw Statement Exceptions are thrown using the throw statement Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown

Checked Exceptions An exception is either checked or unchecked A checked exception either must be caught by a method, or must be listed in the throws clause of any method that may throw or propagate it A throws clause is appended to the method header The compiler will issue an error if a checked exception is not caught or asserted in a throws clause

The throws Statement throws clause specifies the exceptions a method throws. 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. Method can throw exceptions of the classes listed in its throws clause or of their subclasses. Clients of a method with a throws clause are thus informed that the method may throw exceptions.

Unchecked Exceptions An unchecked exception does not require explicit handling, though it could be processed that way The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants