Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Similar documents
Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

ECE 122. Engineering Problem Solving with Java

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Object Oriented Programming

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

COMP1008 Exceptions. Runtime Error

Internal Classes and Exceptions

Object Oriented Programming. Week 7 Part 1 Exceptions

Exception-Handling Overview

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Defensive Programming. Ric Glassey

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

6.Introducing Classes 9. Exceptions

Chapter 3 Java Exception

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Exceptions. Examples of code which shows the syntax and all that

Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java. Xiaoqing Lv 1 1 huihua College Of Hebei Normal University,

Chapter 13 Exception Handling

Comp 249 Programming Methodology Chapter 9 Exception Handling

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Java Loose Ends. 11 December 2017 OSU CSE 1

14. Exception Handling

Programming II (CS300)

Program Correctness and Efficiency. Chapter 2

Lecture 19 Programming Exceptions CSE11 Fall 2013

Data Structures. 02 Exception Handling

BBM 102 Introduction to Programming II Spring Exceptions

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Object Oriented Programming

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Data Structure. Recitation IV

BBM 102 Introduction to Programming II Spring 2017

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Sri Vidya College of Engineering & Technology Question Bank

Programming II (CS300)

Fundamentals of Object Oriented Programming

Exceptions in Java

Object Oriented Programming Exception Handling

Practical Session #09 Exceptions & Networking. Tom Mahler

Introduction Unit 4: Input, output and exceptions

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Exception Handling Generics. Amit Gupta

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

CS 3 Introduction to Software Engineering. 3: Exceptions

Download link: Java Exception Handling

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

2.6 Error, exception and event handling

Chapter 14. Exception Handling and Event Handling

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Exceptions. Gunnar Gotshalks EX 1

Chapter 14. Exception Handling and Event Handling ISBN

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

National University. Faculty of Computer Since and Technology Object Oriented Programming

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Abstract Classes, Exceptions

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Content 25/03/15. Advanced Programming

Assertions and Exceptions Lecture 11 Fall 2005

Unit III Rupali Sherekar 2017

Programming Languages and Techniques (CIS120)

Chapter 14. Exception Handling and Event Handling 异常处理和事件处理. 孟小亮 Xiaoliang MENG, 答疑 ISBN

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Here is a hierarchy of classes to deal with Input and Output streams.

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Vendor: Oracle. Exam Code: 1Z Exam Name: Java SE 7 Programmer I. Version: Demo

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

C16b: Exception Handling

Chapter 12 Exception Handling

Exception Handling in C++

Exceptions Handling Errors using Exceptions

Main concepts to be covered. Handling errors. Some causes of error situations. Not always programmer error. Defensive programming.

CSCI 261 Computer Science II

Why Exceptions? (1.1) Exceptions. Why Exceptions? (1.2) Caller vs. Callee. EECS2030 B: Advanced Object Oriented Programming Fall 2018

Exceptions. EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG

Check out FilesAndExceptions from SVN. Exam 2 Review File I/O, Exceptions Vector Graphics Project

CS159. Nathan Sprague

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Introduction to Software Design

Java Exceptions Version June 2009

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

CS193j, Stanford Handout #25. Exceptions

CSE 331 Software Design & Implementation

Transcription:

Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor

Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions What are Checked Exceptions? Three Components to Handling Exceptions The try, catch, and finally Blocks Exceptions Thrown by a Method How to Throw Exceptions The throw Statement 2

What is an Exception? The Java programming language uses exceptions to handle errors and other exceptional events What is an exception? An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. The term exception is shorthand for the phrase "exceptional event." 3

Throwing an Exception When an error occurs within a method, the method creates an object and hands it off to the runtime system The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception 4

Throwing an Exception After a method throws an exception, the runtime system attempts to find something to handle it The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred The list of methods is known as the call stack 5

Exception Handler The Call Stack The runtime system searches the call stack for a method that contains a block of code that can handle the exception This block of code is called an exception handler 6

Exception Handler The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called When an appropriate handler is found, the runtime system passes the exception to the handler What is considered an appropriate handler? An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler 7

Exception Handler The exception handler chosen is said to catch the exception If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the runtime system (and, consequently, the program) terminates 8

Exception Handler Searching the call stack for the exception handler 9

Catch or Specify Requirement The Java runtime system requires that a method must either catch or specify all checked exceptions that can be thrown by that method This means that code that might throw certain exceptions must be enclosed by either of the following: A try statement that catches the exception. The try must provide a handler for the exception (explained later) A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception (explained later) 10

Catch or Specify Requirement Code that fails to honour the Catch or Specify Requirement will not compile Note: not all exceptions are subject to the Catch or Specify Requirement To understand why, we need to look at the three basic categories of exceptions, only one of which is subject to the Requirement 11

Three Kinds of Exceptions The first kind of exception is the checked exception These are exceptional conditions that a wellwritten application should anticipate and recover from For example, attempting to open a file using a user-supplied name of a nonexistent file. This will throw an java.io.filenotfoundexception A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name 12

Three Kinds of Exceptions The second kind of exception is the error These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from For example, unable to read a file because of a hardware or system malfunction. The unsuccessful read will throw java.io.ioerror Errors are not subject to the Catch or Specify Requirement. 13

Three Kinds of Exceptions The third kind of exception is the runtime exception These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These include: arithmetic exceptions (such as when dividing by zero), pointer exceptions (such as trying to access an object through a null reference), indexing exceptions (such as attempting to access an array element through an index that is too large or too small) 14

Three Kinds of Exceptions Runtime exceptions are not subject to the Catch or Specify Requirement Errors and runtime exceptions are collectively known as unchecked exceptions 15

What are Checked Exceptions? Checked exceptions are subject to the Catch or Specify Requirement Note: the compiler ensures that checked exceptions are caught or specified The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. The checked exception classes are all exception classes other than the unchecked exception classes. 16

Three Components to Handling Exceptions There are three exception handler components to writing an exception handler. try block catch block finally block 17

The try Block The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block In general, a try block looks like the following The segment in the example labelled code contains one or more legal lines of code that could throw an exception 18

The try Block For example, a try block when creating a new file for writing. If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it 19

The try Block Two approaches If you have a block of code that might throw several exceptions, there are two approaches to handling them You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each Or, you can put all the code within a single try block and associate multiple handlers with it 20

The catch Block You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block 21

The catch Block Each catch block is an exception handler and handles the type of exception indicated by its argument The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class The handler can refer to the exception with name 22

The catch Block The catch block contains code that is executed if and when the exception handler is invoked The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown The system considers it a match if the thrown object can legally be assigned to the exception handler's argument 23

The catch Block An adaption of an example from http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html 24

The catch Block An excerpt of an example from http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html Both handlers print an error message. The second handler does nothing else. By catching any IOException that's not caught by the first handler, it allows the program to continue executing The first handler, in addition to printing a message, throws a user-defined exception (to be covered later) You might want to throw a user-defined exception if you want your program to handle an exception in this situation in a specific way. 25

The catch Block Exception handlers can do more than just print error messages or halt the program They can do error recovery, prompt the user to make a decision, or propagate the error up to a higherlevel handler using chained exceptions 26

The finally Block The finally block always executes when the try block exits This ensures that the finally block is executed even if an unexpected exception occurs But finally is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated 27

Common Error Trap If the JVM exits while the try or catch code is being executed, then the finally block may not execute Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues 28

The finally Block An example of a finally block that ensures the Printwriter stream is closed. Note: All File input and output streams should be closed before exiting the program. The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered 29

A Complete Example An adapted example from http://docs.oracle.com/javase/tutorial/essential/exceptions/putittogether.html 30

Exceptions thrown by a Method If a method doesn't catch the checked exceptions that can occur within it, the method must specify that it can throw these exceptions To specify a method can throw exceptions, add a throws clause to the method declaration The throws clause comprises the throws keyword followed by a comma-separated list of all the exceptions thrown by that method 31

Exceptions thrown by a Method The clause goes after the method name and argument list and before the brace that defines the scope of the method An example: Remember that ArrayIndexOutOfBoundsException is an unchecked exception; including it in the throws clause is not mandatory. You could just write the following 32

How to Throw Exceptions Before you can catch an exception, some code somewhere must throw one Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment Regardless of what throws the exception, it's always thrown with the throw statement 33

How to Throw Exceptions The Java platform provides numerous exception classes All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program You can also create your own exception classes to represent problems that can occur within the classes you write 34

The throw Statement All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement 35

The throw Statement Let's look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object 36

The throw Statement The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0), pop instantiates a new EmptyStackException object (a member of java.util) and throws it Note that the declaration of the pop method does not contain a throws clause. EmptyStackException is not a checked exception, so pop is not required to state that it might occur 37

Required Reading The slides are based on the the Exceptions trail of the Online Oracle Java Tutorial The Exceptions trail of the Online Oracle Java Tutorial is required reading. It may be viewed at: http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html 38