More on Exception Handling

Similar documents
More on Exception Handling

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming

C16b: Exception Handling

ECE 122. Engineering Problem Solving with Java

BBM 102 Introduction to Programming II Spring Exceptions

Fundamentals of Object Oriented Programming

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

BBM 102 Introduction to Programming II Spring 2017

For more details on SUN Certifications, visit

Full file at Chapter 2 - Inheritance and Exception Handling

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

EXCEPTION HANDLING. Summer 2018

Exception-Handling Overview

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

ITI Introduction to Computing II

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

ITI Introduction to Computing II

What are Exceptions?

CSC207H: Software Design. Exceptions. CSC207 Winter 2018


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

Exceptions. CSC207 Winter 2017

Introduction to Software Design

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

Programming II (CS300)

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Exceptions - Example. Exceptions - Example

CSCI 261 Computer Science II

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

COE318 Lecture Notes Week 10 (Nov 7, 2011)

EXCEPTIONS. Java Programming

Programming II (CS300)

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

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

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Data Structures. 02 Exception Handling

Correctness and Robustness

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

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

School of Informatics, University of Edinburgh

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

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

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

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

Chapter 12 Exception Handling

Software Practice 1 - Error Handling

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

More on Objects in JAVA TM

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

Title. Java Just in Time. John Latham. February 8, February 8, 2018 Java Just in Time - John Latham Page 1(0/0)

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Exceptions and Error Handling

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Exceptions Handling Errors using Exceptions

Chapter 13 Exception Handling

Java Errors and Exceptions. Because Murphy s Law never fails

Exception Handling. Chapter 11. Java By Abstraction Chapter 11. Outline What Are Exceptions?

Object Oriented Programming

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming

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

Exception Handling in Java

Comp 249 Programming Methodology Chapter 9 Exception Handling

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

CSC 1214: Object-Oriented Programming

Errors and Exceptions

COMP1008 Exceptions. Runtime Error

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

Chapter 14. Exception Handling and Event Handling ISBN

File I/O and Exceptions

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Exception Handling CSCI 201 Principles of Software Development

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. Exception Handling

CS112 Lecture: Exceptions and Assertions

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

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

Recitation 3. 2D Arrays, Exceptions

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary

6.Introducing Classes 9. Exceptions

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

Exception Handling. Exception Handling

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

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

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

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

CS159. Nathan Sprague

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Input-Output and Exception Handling

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

SECTION-1 Q.1.Which two code fragments are most likely to cause a StackOverflowError? (Choose two.)

Transcription:

Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2 http://www.ii.uib.no/~khalid/jac/ Permission is hereby granted to use these lecture slides in conjunction with the book. Modified: 11/12/09 Java Actually 18: More on Exception Handling 18-1/20

Overview Overview of exception classes Explicitly throwing an exception: the throw clause try block with multiple catch blocks Typical programming errors in exception handling Executing the finally block Java Actually 18: More on Exception Handling 18-2/20

Partial hierarchy of exception classes (Figure 18.1) java.lang Throwable java.io IOException EOFException FileNotFoundException... Exception ClassNotFoundException RuntimeException NullPointerException ArithmeticException... Error AssertionError ClassCastException IllegalArgumentException NumberFormatException... IndexOutOfBoundsException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException...... The grey-coloured classes (and their subclasses) represent unchecked exceptions. Java Actually 18: More on Exception Handling 18-3/20

Selected methods from the Throwable class (Table 18.1) Method String getmessage() void printstacktrace() Description Returns the string in the exception. The string provides more explanation of the exception. Prints on the terminal the stack trace at the time the exception was thrown. Java Actually 18: More on Exception Handling 18-4/20

Class Exception and checked exceptions Exceptions of the type Exception class and its subclasses, with the exception of subclasses of RuntimeException class, are called checked exceptions. The compiler checks that a method that throws a checked exception, also explicitly handles the exception. Class RuntimeException and unchecked exceptions The class RuntimeException and its subclasses represent exceptions that represent typical unforeseen errors, such as programming errors. Exceptions that are defined by the class RuntimeException and its subclasses is called unchecked exceptions. It is not necessary that they be caught in the program, but the cause of the error must be corrected in the program. Class Error The subclass AssertionError is used to signal that an assertion does not hold during the execution. Such exceptions should not be caught. Java Actually 18: More on Exception Handling 18-5/20

Explicitly throwing an exception A program can explicitly throw an exception with the throw statement: throw new ArithmeticException ("Distance and time cannot be < 0"); Executing a throw statement interrupts the normal execution of the program, and the exception is propagated. It is common to use an appropriate exception class to define an error situation and provide supplementary information about the exception in the constructor call. In Program 18.1, the program execution will result in an ArithmeticException being thrown in the method calculatespeed(), (4). This exception will propagate and will be handled by the catch block in main() method. From this point, normal execution of the program will continue. Java Actually 18: More on Exception Handling 18-6/20

Throwing an exception programmatically (Program 18.1) public class Speed4 { public static void main(string[] args) { System.out.println("Entering main()."); try { printspeed(-100, 10); // (1) Distance < 0. catch (ArithmeticException exception) { // (2) System.out.println(exception + " (handled in main())"); System.out.println("Returning from main()."); private static void printspeed(int kilometers, int hours) { System.out.println("Entering printspeed()."); int speed = calculatespeed(kilometers, hours); System.out.println("Speed = " + kilometers + "/" + hours + " = " + speed); System.out.println("Returning from printspeed()."); Java Actually 18: More on Exception Handling 18-7/20

private static int calculatespeed(int distance, int time) { System.out.println("Calculating speed."); if (distance < 0 time < 0) // (3) throw new ArithmeticException("distance and time" + " cannot be < 0"); // (4) return distance/time; Output from the program: Entering main(). Entering printspeed(). Calculating speed. java.lang.arithmeticexception: distance and time cannot be < 0 (handled in main()) Returning from main(). Java Actually 18: More on Exception Handling 18-8/20

Handling several types of exceptions If the code in a try block can throw different types of exceptions, we can specify one catch block for each type of exception after the try block (Program 18.2). Indexing in the string array args, (3) and (4), can throw an unchecked ArrayIndexOutOfBoundsException unless at least two strings are specified on the command line. Converting to integer with the parseint() method, (3) and (4), can throw an unchecked NumberFormatException if any of the strings contain characters that can not be part of an integer. Java Actually 18: More on Exception Handling 18-9/20

try block with several catch blocks (Program 18.2) public class Speed5 { public static void main(string[] args) { System.out.println("Entering main()."); int arg1, arg2; // (1) try { // (2) arg1 = Integer.parseInt(args[0]); // (3) arg2 = Integer.parseInt(args[1]); // (4) catch (ArrayIndexOutOfBoundsException exception) { // (5) System.out.println("Specify both kilometers and hours."); System.out.println("Usage: java Speed5 <kilometers> <hours>"); System.out.println(exception + " (handled in main())"); return; catch (NumberFormatException exception) { // (6) System.out.println("Kilometers and hours must be integers."); System.out.println("Usage: java Speed5 <kilometers> <hours>"); System.out.println(exception + " (handled in main())"); return; printspeed(arg1, arg2); // (7) System.out.println("Returning from main()."); Java Actually 18: More on Exception Handling 18-10/20

private static void printspeed(int kilometers, int hours) { System.out.println("Entering printspeed()."); try { int speed = calculatespeed(kilometers, hours); System.out.println("Speed = " + kilometers + "/" + hours + " = " + speed); catch (ArithmeticException exception) { System.out.println(exception + " (handled in printspeed())"); System.out.println("Returning from printspeed()."); private static int calculatespeed(int distance, int time) { System.out.println("Calculating speed."); if (distance < 0 time < 0) throw new ArithmeticException("distance and time cannot be < 0"); return distance/time; Java Actually 18: More on Exception Handling 18-11/20

Output from the program: > java Speed5 100 Entering main(). Specify both kilometers and hours. Usage: java Speed5 <kilometers> <hours> java.lang.arrayindexoutofboundsexception: 1 (handled in main()) > java Speed5 200 4u Entering main(). Kilometers and hours must be integers. Usage: java Speed5 <kilometers> <hours> java.lang.numberformatexception: For input string: "4u" (handled in main()) > java Speed5 200-10 Entering main(). Entering printspeed(). Calculating speed. java.lang.arithmeticexception: distance and time cannot be < 0 (handled in printspeed()) Returning from printspeed(). Returning from main(). > java Speed5 200 0 Entering main(). Entering printspeed(). Calculating speed. java.lang.arithmeticexception: / by zero (handled in printspeed()) Returning from printspeed(). Returning from main(). Java Actually 18: More on Exception Handling 18-12/20

Typical programming errors in exception handling A parameter type in a catch block can shadow other exception types in the subsequent catch blocks. For example, the superclass RuntimeException in the catch block (1) shadows the subclass ArithmeticException in the catch block (2): try {... catch (RuntimeException exception1) {... // (1) catch (ArithmeticException exception2) {... // (2) Exceptions of type ArithmeticException are caught by the catch block (1) and never by the catch block (2), since objects of subclasses can be assigned to a superclass reference. The compiler will warn of such cases. Do not catch all exceptions in one catch block by using more general exception classes, such as Exception and RuntimeException. Using specific exception classes, often with multiple catch blocks, are recommended in the try-catch construct to improve program understanding. Java Actually 18: More on Exception Handling 18-13/20

Defining new exceptions It is recommended to define new subclasses of the class Exception. The new exception is then automatically checked by the compiler. class SpeedCalculationException extends Exception { SpeedCalculationException(String str) { super(str); It is usually sufficient to define only a constructor that takes a string parameter. Java Actually 18: More on Exception Handling 18-14/20

Executing the finally block A finally block can occur with a try block. A catch block does not necessarily need to be specified. The code in the finally block is always executed if the try block is executed. It does not matter if an exception was thrown or not. "Cleanup Code" may be put in a finally block so it will always be executed. The class Speed7 illustrates executing a finally block. A finally block is specified at (4), with the corresponding try block at (1). Printout shows that the code in the finally block will always be executed if the try block is executed. Java Actually 18: More on Exception Handling 18-15/20

public class Speed7 { public static void main(string[] args) { System.out.println("Entering main()."); try { //(1) // printspeed(100, 20); //(2a) printspeed(-100,20); //(2b) catch (SpeedCalculationException exception) { //(3) System.out.println(exception + " (handled in main())"); finally { //(4) System.out.println("Command to use: java Speed7"); System.out.println("Returning from main()."); Java Actually 18: More on Exception Handling 18-16/20

private static void printspeed(int kilometers, int hours) throws SpeedCalculationException { //(5) System.out.println("Entering printspeed()."); double speed = calculatespeed(kilometers, hours); System.out.println("Speed = " + kilometers + "/" + hours + " = " + speed); System.out.println("Returning from printspeed()."); private static int calculatespeed(int distance, int time) throws SpeedCalculationException { //(6) System.out.println("Calculating speed."); if (distance < 0 time <= 0) throw new SpeedCalculationException("distance and time " + "must be > 0"); //(7) return distance/time; Java Actually 18: More on Exception Handling 18-17/20

Running the program with the code line (2a): printspeed(100, 20); gives the following output: Entering main(). Entering printspeed(). Calculating speed. Speed = 100/20 = 5.0 Returning from printspeed(). Command to use: java Speed7 Returning from main(). Running the program with the code line (2b): printspeed(100, 0); // (2a) // (2b) gives the following output: Entering main(). Entering printspeed(). Calculating speed. SpeedCalculationException: distance and time must be > 0 (handled in main()) Command to use: java Speed7 Returning from main(). Note that the execution of the method printspeed() was stopped after the finally block was executed. Java Actually 18: More on Exception Handling 18-18/20

Exception handling and inheritance A method in the subclass can only specify in its throws clause a subset of the exception types specified in the throws clause of the method it is overriding from a superclass. // Class A public void methodwithmanyexceptions() throws Exception1, Exception2, Exception3 {...... // In subclass B which extends superclass A public void methodwithmanyexceptions() throws Exception1, Exception3 {... Java Actually 18: More on Exception Handling 18-19/20

Summary of exception handling "Throw and catch" rule for checked exceptions: A method can catch the exceptions it throws, and handle them in catch blocks. The checked exceptions that a method can throw and not catch, must be declared in a throws clause of the method. A method can programmatically throw an exception using the throw statement.... methodname(...) throws Exception 1, Exception 2,..., Exception n {... try { // code resulting in one of the following exceptions being thrown: // Exception 1,..., Exception n og Exception a,..., Exception m throw new Exception i (); // throws an exception of type Exception i catch (Exception j e j ) { // catches exception of type Exception j // code to handle Exception e j... catch (Exception k e k ) { // catches exception of type Exception k // code to handle Exception e k finally {... // Code that is always executed if try block is executed.... try-catch-finally block Java Actually 18: More on Exception Handling 18-20/20