Chapter 12 Exception Handling

Similar documents
Chapter 13 Exception Handling

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

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO

Motivations. Chapter 12 Exceptions and File Input/Output

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

Exception-Handling Overview

Java Errors and Exceptions. Because Murphy s Law never fails

BBM 102 Introduction to Programming II Spring Exceptions

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

BBM 102 Introduction to Programming II Spring 2017

ECE 122. Engineering Problem Solving with Java

Correctness and Robustness

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

Programming II (CS300)

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

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

Programming II (CS300)

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

Data Structures. 02 Exception Handling

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

CSCI 261 Computer Science II

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

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

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

EXCEPTION HANDLING. Summer 2018

CSC 1214: Object-Oriented Programming

Exception Handling. Handling bad user input. Dr. Siobhán Drohan Maireád Meagher. Produced by:

More on Exception Handling

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

More on Exception Handling

COE318 Lecture Notes Week 10 (Nov 7, 2011)

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

What are Exceptions?

CSE 143 Java. Exceptions 1/25/

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

Defensive Programming. Ric Glassey

Fundamentals of Object Oriented Programming

Exceptions Handling Errors using Exceptions

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

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

CS159. Nathan Sprague

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

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

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Input-Output and Exception Handling

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

ITI Introduction to Computing II

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

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

ITI Introduction to Computing II

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

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

Full file at Chapter 2 - Inheritance and Exception Handling

Exceptions and Error Handling

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

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

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

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

17. Handling Runtime Problems

CS 209 Programming in Java #10 Exception Handling

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

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

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

Exceptions. CSC207 Winter 2017

Typecasts and Dynamic Dispatch. Dynamic dispatch

CS 3 Introduction to Software Engineering. 3: Exceptions

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

JAVA Ch. 4. Variables and Constants Lawrenceville Press

C16b: Exception Handling

Introduction to Software Design

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

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

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

16-Dec-10. Consider the following method:

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

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

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

Comp 249 Programming Methodology Chapter 9 Exception Handling

CS159. Nathan Sprague

Object Oriented Programming Exception Handling

Intro to Computer Science II. Exceptions

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Program Correctness and Efficiency. Chapter 2

Java Exception. Wang Yang

Chapter 5. Exceptions. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

Exception Handling in Java

Programming Languages and Techniques (CIS120)

Exceptions - Example. Exceptions - Example

Unit 5 - Exception Handling & Multithreaded

Introduction to Computer Science II CS S-22 Exceptions

WOSO Source Code (Java)

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Transcription:

Chapter 12 Exception Handling 1

Motivations Goal: Robust code. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? Answer: Exception Handling. Exceptions are objects (from built-in classes). 2

Exception Handling Exception handling enables a method to throw an exception to its caller. Without this capability, a method must handle the exception or terminate the program. Exceptions are similar to methods, they return values (exceptions). 3

Exception Types/Classes Error types: -System Errors - Program Errors - Runtime Errors Exception ClassNotFoundException IOException ArithmeticException NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Many more classes IllegalArgumen texception Many more classes LinkageError Error VirtualMachineError Many more classes Unchecked Exceptions: System Errors and Runtime Errors Checked Exception: IO errors and Class Errors, must check them! 4

System Errors ClassNotFoundException IOException ArithmeticException Exception NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Many more classes IllegalArgumentException System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. Error LinkageError VirtualMachineError Many more classes Many more classes 5

Program Errors Exception describes errors caused by the program and external circumstances. These errors can be caught and handled by your code. Exception ClassNotFoundException IOException RuntimeException ArithmeticException NullPointerException IndexOutOfBoundsException Object Throwable Many more classes IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Many more classes 6

Runtime Errors Runtime errors are thrown by JVM during runtime due to programming errors, such as index outof-bound, numeric error due to math expressions, invalid pointers, and casting issues and incompatible parameters. Exception ClassNotFoundException IOException RuntimeException ArithmeticException NullPointerException IndexOutOfBoundsException Object Throwable Many more classes IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Many more classes 7

Checked vs. Unchecked Exceptions Classes RuntimeException and Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions. 8

Unchecked Exceptions ClassNotFoundException IOException ArithmeticException Exception NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Many more classes IllegalArgumentException Many more classes LinkageError Error VirtualMachineError Unchecked exception. Many more classes 9

Unchecked Exceptions Examples Unchecked exceptions reflect programming logic errors that are not recoverable. For example, NullPointerException: Access an object through a reference variable before an object is assigned to it. IndexOutOfBoundsException: Access an element in an array outside the bounds of the array. ArithmeticException: Invalid math operation. IllegalArgumentException: Parameter mismatch. 10

When to Throw Exceptions If you can handle the exception in the method where it occurs, there is no need to throw it. If you want the exception to be processed (handled) by its caller, you should create an exception object and throw it back to the caller. 11

import java.util.scanner; Example public class Quotient { public static void main(string[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter two integers: "); int number1 = input.nextint(); int number2 = input.nextint(); System.out.println(number1 + "/" + number2 + " is " + (number1 / number2)); // runtime error if number 2 = 0!! 12

Example with try-catch Block import java.util.scanner; public class QuotientWithException { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter two integers: "); int number1 = input.nextint(); int number2 = input.nextint(); int result = number1/number2;// may cause runtime error System.out.println(number1 + " / " + number2 + " is " + result); catch (ArithmeticException ex) { System.out.println("Exception: cannot divided an " + "integer by zero "); System.out.println("Execution continues..."); 13

Example with try-catch Block import java.util.scanner; public class QuotientWithException { public static int quotient(int number1, int number2) { { if (number2 == 0) throw new ArithmeticException("Cannot divide by be zero"); return number1 / number2; public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter two integers: "); int number1 = input.nextint(); int number2 = input.nextint(); int result = quotient(number1, number2); // method call System.out.println(number1 + " / " + number2 + " is " + result); catch (ArithmeticException ex) { System.out.println("Exception: " + ex.getmessage()); System.out.println("Execution continues..."); 14

Library Methods Throw Exceptions import java.util.*; public class InputMismatchExceptionDemo { public static void main(string[] args) { Scanner input = new Scanner(System.in); boolean continueinput = true; do { System.out.print("Enter an integer: "); int number = input.nextint(); // Display the result System.out.println("Number entered: " + number); continueinput = false; catch (InputMismatchException ex) { System.out.println("Try again, incorrect input. " + "Integer is required)"); input.nextline(); // discard input while (continueinput); 15

Declaring, Throwing, and Catching Exceptions catch exception method1() { invoke method2; catch (Exception ex) { Process exception; method2() throws Exception { if (an error occurs) { throw new Exception(); declare exception throw exception 16

Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void mymethod() throws IOException public void mymethod() throws IOException, OtherException 17

Throwing Exceptions When the program detects an error, the program can create an instance of an appropriate exception type and throw it to the caller. This is known as throwing an exception. Here is an example, OR throw new TheException(); TheException ex = new TheException(); throw ex; 18

Throwing Exceptions Example // Set a new radius public void setradius(double newradius) throws IllegalArgumentException { if (newradius >= 0) radius = newradius; else throw new IllegalArgumentException( "Radius cannot be negative"); 19

Catching Exceptions by Caller statements;//statements may throw exceptions catch (Exception1 exvar1) { handler for exception1; catch (Exception2 exvar2) { handler for exception2;... catch (ExceptionN exvar3) { handler for exceptionn; 20

Catching Exceptions - Call Stack main method {...... invoke method1; statement1; catch (Exception1 ex1) { Process ex1; statement2; method1 {...... invoke method2; statement3; catch (Exception2 ex2) { Process ex2; statement4; method2 {...... invoke method3; statement5; catch (Exception3 ex3) { Process ex3; statement6; An exception is thrown in method3 Call Stack method3 method2 method2 method1 method1 method1 main method main method main method main method 21

Catch or Declare Checked Exceptions Suppose p2 is defined as follows: void p2() throws IOException { if (file.exists()){ throw new IOException("File already exists");... HW: Type, compile, and run code in listing 12.12, page 474. 22

Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b). void p1() { p2(); catch (IOException ex) {... (a) void p1() throws IOException { p2(); (b) 23

The finally Clause statements; catch(theexception ex) { handling ex; finally { finalstatements; // always executes 24

animation Trace a Program Execution - 1 statements; catch(theexception ex) { handling ex; finally { finalstatements; Next statement; Suppose no exceptions in the statements 25

animation Trace a Program Execution - 1 statements; catch(theexception ex) { handling ex; finally { finalstatements; The final block is always executed Next statement; 26

animation Trace a Program Execution - 1 statements; catch(theexception ex) { handling ex; finally { finalstatements; Next statement in the method is executed Next statement; 27

animation Trace a Program Execution - 2 statement1; statement2; statement3; catch(exception1 ex) { handling ex; finally { finalstatements; Suppose an exception of type Exception1 is thrown in statement2 Next statement; 28

animation Trace a Program Execution - 2 statement1; statement2; statement3; //skipped catch(exception1 ex) { handling ex; finally { finalstatements; The exception is handled. Next statement; 29

animation Trace a Program Execution - 2 statement1; statement2; statement3; //skipped catch(exception1 ex) { handling ex; finally { finalstatements; The final block is always executed. Next statement; 30

animation Trace a Program Execution - 2 statement1; statement2; statement3; //skipped catch(exception1 ex) { handling ex; finally { finalstatements; The next statement in the method is now executed. Next statement; 31

animation Trace a Program Execution - 3 statement1; statement2; statement3; catch(exception1 ex) { handling ex; catch(exception2 ex) { handling ex; throw ex; finally { finalstatements; statement2 throws an exception of type Exception2. Next statement; 32

animation Trace a Program Execution - 3 statement1; statement2; statement3; //skipped catch(exception1 ex) { handling ex; catch(exception2 ex) { handling ex; throw ex; finally { finalstatements; Handling exception Next statement; 33

animation Trace a Program Execution - 3 statement1; statement2; statement3; //skipped catch(exception1 ex) { handling ex; catch(exception2 ex) { handling ex; throw ex; finally { finalstatements; Execute the final block Next statement; 34

animation Trace a Program Execution - 3 statement1; statement2; statement3; //skipped catch(exception1 ex) { handling ex; catch(exception2 ex) { handling ex; throw ex; //control returns to caller method finally { finalstatements; Next statement; //skipped Rethrow the exception and control is transferred to the caller 35

animation Trace a Program Execution - 3 statement1; statement2; statement3; //skipped catch(exception1 ex) { handling ex; catch(exception2 ex) { handling ex; throw ex; finally { finalstatements; Control is back to the caller method. Next statement; //skipped 36

When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code //replace with if statement System.out.println(refVar.toString()); catch (NullPointerException ex) { System.out.println("refVar is null"); 37

When to Use Exceptions is better to be replaced by if (refvar!= null) System.out.println(refVar.toString()); else System.out.println("refVar is null"); 38

Defining Custom Exception Classes Use the exception classes in the API whenever possible. Define custom exception classes if the predefined classes are not sufficient. Define custom exception classes by extending Exception or a subclass of Exception. See Listing 13.8, page 470, the setradius method throws an exception if the radius is negative. 39

Example Custom Exception Class public class InvalidRadiusException extends Exception { private double radius; // Construct an exception public InvalidRadiusException(double radius) { super("invalid radius " + radius); this.radius = radius; // Return the radius public double getradius() { return radius; 40

Example Custom Exception Class // Code from class CircleWithCustomException // Construct a circle with radius 1 public CircleWithCustomException() throws InvalidRadiusException { this(1.0); // Construct a circle with a specified radius public CircleWithCustomException(double newradius) throws InvalidRadiusException { setradius(newradius); numberofobjects++; // Set a new radius public void setradius(double newradius) throws InvalidRadiusException { if (newradius >= 0) radius = newradius; else throw new InvalidRadiusException(newRadius); 41

End of Slides