C16b: Exception Handling

Similar documents
C17: File I/O and Exception Handling

More on 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

More on Exception Handling

BBM 102 Introduction to Programming II Spring Exceptions

ECE 122. Engineering Problem Solving with Java

Fundamentals of Object Oriented Programming

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

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

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

CSC 1214: Object-Oriented Programming

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

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

CSCI 261 Computer Science II

For more details on SUN Certifications, visit

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

Exception Handling in Java

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

Programming II (CS300)

CS159. Nathan Sprague

Exception Handling. Exception Handling

Object Oriented Programming

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

ITI Introduction to Computing II

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

What are Exceptions?

ITI Introduction to Computing II

Exceptions - Example. Exceptions - Example

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

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

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

Object Oriented Programming Exception Handling

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

Recitation 3. 2D Arrays, Exceptions

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Programming II (CS300)

Exception Handling Advanced Programming Techniques

CS159. Nathan Sprague

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Full file at Chapter 2 - Inheritance and Exception Handling

COMP1008 Exceptions. Runtime Error

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

Introductory Programming Exceptions and I/O: sections

EXCEPTIONS. Fundamentals of Computer Science I

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

CS 3 Introduction to Software Engineering. 3: Exceptions

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

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

Chapter 13 Exception Handling

Exceptions Handling Errors using Exceptions

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

Unit 5 - Exception Handling & Multithreaded

EXCEPTION HANDLING. Summer 2018

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

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

Correctness and Robustness

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

Java Programming Language Mr.Rungrote Phonkam

Defensive Programming. Ric Glassey

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

Java Errors and Exceptions. Because Murphy s Law never fails

Download link: Java Exception Handling

Programming Languages and Techniques (CIS120)

Introduction to Computer Science II CS S-22 Exceptions

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

Java Exception. Wang Yang

Chapter 12 Exception Handling

Input-Output and Exception Handling

Exceptions and Error Handling

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


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

17. Handling Runtime Problems

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

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


Internal Classes and Exceptions

Exceptions in Java

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

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

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

EXCEPTIONS. Java Programming

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exception-Handling Overview

Object Oriented Programming

Exceptions. What exceptional things might our programs run in to?

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

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

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

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

Std 12 Lesson-10 Exception Handling in Java ( 1

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

Data Structures. 02 Exception Handling

Typecasts and Dynamic Dispatch. Dynamic dispatch

Transcription:

CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1

Outline Exceptions Catch and handle exceptions (try/catch) Forward exceptions Specify requirement for methods (throws) Customize exceptions and types of exceptions Checked and unchecked exception Some Best Practice 3/28/2018 CUNY Brooklyn College 2

What may can go wrong? A simple Java expression evaluator public class SimpleExpr { public static void main(string[] args) { int d1 = Integer.parseInt(args[0]); int d2 = Integer.parseInt(args[2]); int result; switch(args[1]) { case "+": result = d1 + d2; System.out.println(String.join(" ", args) + " = " + result); break; case "-": result = d1 - d2; System.out.println(String.join(" ", args) + " = " + result); break; case "*": result = d1 * d2; System.out.println(String.join(" ", args) + " = " + result); break; case "/": result = d1 / d2; System.out.println(String.join(" ", args) + " = " + result); break; 3/28/2018 CUNY Brooklyn College 3

Things can go wrong $ java SimpleExpr Exception in thread "main" java.lang.arrayindexoutofboundsexception: 0 at edu.cuny.brooklyn.cisc3120.simpleexpr.simpleexpr.main(simpleexpr.java:3) $ java SimpleExpr 1.0 + 2.0 Exception in thread "main" java.lang.numberformatexception: For input string: "1.0" at java.lang.numberformatexception.forinputstring(unknown Source) at java.lang.integer.parseint(unknown Source) at java.lang.integer.parseint(unknown Source) at edu.cuny.brooklyn.cisc3120.simpleexpr.simpleexpr.main(simpleexpr.java:3) $ java SimpleExpr 3 / 0 Exception in thread "main" java.lang.arithmeticexception: / by zero at edu.cuny.brooklyn.cisc3120.simpleexpr.simpleexpr.main(simpleexpr.java:12) 3/28/2018 CUNY Brooklyn College 4

Exceptions Java uses exceptions to handle errors and other exceptional events. Exception: exceptional situations at runtime An event that occurs during the execution of a program that disrupts the normal flow of instructions. Examples Division-by-zero Access an array element that does not exist When the exception situation occurs, Java throws an exception. 3/28/2018 CUNY Brooklyn College 5

Throws an Exception The method where an error occurs creates an Exception object and hands it off to the Java runtime Exception object, contains Information about error Its type and the state of the program when the error occurred.. 3/28/2018 CUNY Brooklyn College 6

Call Stack Java runtime attempts to find objects and methods to handle it An 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 3/28/2018 CUNY Brooklyn College 7

Example Exception $ java SimpleExpr Exception in thread "main" java.lang.arrayindexoutofboundsexception: 0 at edu.cuny.brooklyn.cisc3120.simpleexpr.simpleexpr.main(simpleexpr.java:3) $ java SimpleExpr 1.0 + 2.0 Exception in thread "main" java.lang.numberformatexception: For input string: "1.0" at java.lang.numberformatexception.forinputstring(unknown Source) at java.lang.integer.parseint(unknown Source) at java.lang.integer.parseint(unknown Source) at edu.cuny.brooklyn.cisc3120.simpleexpr.simpleexpr.main(simpleexpr.java:3) $ java SimpleExpr 3 / 0 Exception in thread "main" java.lang.arithmeticexception: / by zero at edu.cuny.brooklyn.cisc3120.simpleexpr.simpleexpr.main(simpleexpr.java:12) 3/28/2018 CUNY Brooklyn College 8

Example Call Stack $ java SimpleExpr Exception in thread "main" java.lang.arrayindexoutofboundsexception: 0 at edu.cuny.brooklyn.cisc3120.simpleexpr.simpleexpr.main(simpleexpr.java:3) main Java Method call $ java SimpleExpr 1.0 + 2.0 Exception in thread "main" java.lang.numberformatexception: For input string: "1.0" at java.lang.numberformatexception.forinputstring(unknown Source) at java.lang.integer.parseint(unknown Source) at java.lang.integer.parseint(unknown Source) at edu.cuny.brooklyn.cisc3120.simpleexpr.simpleexpr.main(simpleexpr.java:3) forinput String parseint parseint main Java Method call Method call Method call Method call $ java SimpleExpr 3 / 0 Exception in thread "main" java.lang.arithmeticexception: / by zero at edu.cuny.brooklyn.cisc3120.simpleexpr.simpleexpr.main(simpleexpr.java:12) main Java Method call 3/28/2018 CUNY Brooklyn College 9

Example Exception Throws and Catch When an exception happens, what does JVM (Java runtime) do? Error occurs, throws an exception Forward exception Forward exception Forward exception Catch and handle the exception forinputstring parseint parseint main Java Look for appropriate handler Look for appropriate handler Look for appropriate handler Look for appropriate handler Look for appropriate handler 3/28/2018 CUNY Brooklyn College 10

Example Exception Throws and Catch When an exception happens, what does JVM (Java runtime) do? Application developers may, sometimes must decide whether to forward or to catch/handle the exceptions Error occurs, throws an exception Forward exception Forward exception Forward exception Catch and handle the exception forinputstring parseint parseint main Java Look for appropriate handler Look for appropriate handler Look for appropriate handler Look for appropriate handler Look for appropriate handler 3/28/2018 CUNY Brooklyn College 11

Questions? Exception? Call stack? 3/28/2018 CUNY Brooklyn College 12

Catch or Forward? Java code must either to catch or forward exceptions A try statement that catches the exception. The try must provide a handler for the exception. A method can be specified to forward an exception The method must provide a throws clause that lists the exception. 3/28/2018 CUNY Brooklyn College 13

Catching and Handling Exceptions Use the try-catch blocks Use the try-catch-finally blocks To be discussed when we discuss File I/O Use the try with resource blocks To be discussed with we discuss File I/O 3/28/2018 CUNY Brooklyn College 14

Try-catch Example: One Exception Try and catch a single exception try { d1 = Integer.parseInt(args[0]); catch (NumberFormatException e) { System.out.println("SimpleExprImproved must take two integer operants. + args[0] + " is not an integer."); System.exit(-1); try { result = d1 / d2; System.out.println(String.join(" ", args) + " = " + result); catch (ArithmeticException e) { System.out.println("The divisisor cannot be zero."); System.exit(-1); 3/28/2018 CUNY Brooklyn College 15

Try-catch Example: One Exception: Call Stack try { d1 = Integer.parseInt(args[0]); catch (NumberFormatException e) { System.out.println("SimpleExprImproved must take two integer operants. + args[0] + " is not an integer."); System.exit(-1); Error occurs, throws an exception Forward exception Forward exception Catch and handle the exception forinputstring parseint parseint main Java Look for appropriate handler Look for appropriate handler Look for appropriate handler Look for appropriate handler 3/28/2018 CUNY Brooklyn College 16

Try-Catch Example: More Exception Try and catch more than one exceptions try { d1 = Integer.parseInt(args[0]); catch (NumberFormatException e) { System.out.println("SimpleExprImproved must take two integer operants. + args[0] + " is not an integer."); System.exit(-1); catch (ArrayIndexOutOfBoundsException e) { System.out.println("Usage: SimpleExprImproved <integer> <+ - * /> <integer>" return; try { d1 = Integer.parseInt(args[0]); catch (NumberFormatException ArrayIndexOutOfBoundsException e) { System.out.println( Either + args[0] + " is not an integer. + or use it correctly: Usage: SimpleExprImproved <integer> <+ - * /> <integer>"); System.exit(-1); 3/28/2018 CUNY Brooklyn College 17

Questions? Catch and handle an exception? 3/28/2018 CUNY Brooklyn College 18

Forward Exception What if we do want to let a method further up the call stack handle the exception? Specifying the Exceptions thrown by a method 3/28/2018 CUNY Brooklyn College 19

Forward Exception: Example public class SimpleExprThrows { public static void main(string[] args) {... try { result = expr(d1, d2, args[1]); System.out.println(d1 + args[1] + d2 + "=" + result); catch(arithmeticexception e) { System.out.println("The divisor is 0."); public static int expr(int d1, int d2, String operator) throws ArithmeticException { int result = 0; switch(operator) { case "+": result = d1 + d2; break; case "-": result = d1 - d2; break; case "*": result = d1 * d2; break; case "/": result = d1 / d2; return result; 3/28/2018 CUNY Brooklyn College 20

Forward Exception: Example: Call Stack public class SimpleExprThrows { public static void main(string[] args) {... try { result = expr(d1, d2, args[1]);. catch(arithmeticexception e) { public static int expr(int d1, int d2, String operator) throws ArithmeticException { int result = 0; switch(operator) { case "/": result = d1 / d2; return result; Error occurs, throws an exception Catch and handle the exception expr main java Look for appropriate handler Look for appropriate handler 3/28/2018 CUNY Brooklyn College 21

Questions? Forward exceptions via method specification. 3/28/2018 CUNY Brooklyn College 22

Is there a difference? Forward exception: wait a minute, what s really different? Let s examine the call stacks of the two public class SimpleExprThrows { public static int expr(int d1, int d2, String operator) { int result = 0; switch(operator) { case "+": result = d1 + d2; break; case "-": result = d1 - d2; break; case "*": result = d1 * d2; break; case "/": result = d1 / d2; return result; public class SimpleExprThrows { public static int expr(int d1, int d2, String operator) throws ArithmeticException { int result = 0; switch(operator) { case "+": result = d1 + d2; break; case "-": result = d1 - d2; break; case "*": result = d1 * d2; break; case "/": result = d1 / d2; return result; 3/28/2018 CUNY Brooklyn College 23

Checked and Unchecked Exceptions, and Errors Java has three types of exceptions and errors Throwable Checked Exceptions Unchecked Exceptions RuntimeExceptions Errors Checked Exceptions Exception RuntimeException Error Unchecked Exceptions (Errors) Unchecked Exceptions (Runtime Exceptions) 3/28/2018 CUNY Brooklyn College 24

Checked Exceptions Checked Exceptions The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Semantics Exceptional conditions that a well-written application should anticipate and recover from. Subject to the Catch or Specify Requirement. You must either forward it explicitly (via specifying requirement when define a method) or handle it. 3/28/2018 CUNY Brooklyn College 25

Unchecked Exceptions RuntimeException and Error and their subclasses Not subject to the Catch or Specify Requirement Forwarded automatically, if not caught and handled or forwarded explicitly (via specif Semantics The application usually cannot anticipate or recover from. Errors The Error class or subclass of Error RuntimeException The RuntimeException class or subclass of RuntimeException 3/28/2018 CUNY Brooklyn College 26

Error and RuntimeException Errors Semantics: exceptional conditions that are external to the application. Example: hardware failure: disk I/O error after a file is open, and read will fail and cannot recover from it. Runtime exceptions Your file is on a USB drive. While your app is reading the file, you unplug the drive. Semantics: exceptional conditions that are internal to the application. Example: logical error: passed a string in a non-integer form to Integer.parseInt() that cannot recover from it (but you may avoid it, if not the first time) 3/28/2018 CUNY Brooklyn College 27

Is there a difference? ArithmeticException is a RuntimeException, it will be forwarded automatically if not explicitly public class SimpleExprThrows { public static int expr(int d1, int d2, String operator) { int result = 0; switch(operator) { case "+": result = d1 + d2; break; case "-": result = d1 - d2; break; case "*": result = d1 * d2; break; case "/": result = d1 / d2; return result; public class SimpleExprThrows { public static int expr(int d1, int d2, String operator) throws ArithmeticException { int result = 0; switch(operator) { case "+": result = d1 + d2; break; case "-": result = d1 - d2; break; case "*": result = d1 * d2; break; case "/": result = d1 / d2; return result; 3/28/2018 CUNY Brooklyn College 28

Questions Checked exceptions, runtime exceptions, and errors 3/28/2018 CUNY Brooklyn College 29

Customize or Raise an Exception? Any code can throw an exception. Use the throw statement. Purposes Raises an exception Customize an exception Create new types of exceptions 3/28/2018 CUNY Brooklyn College 30

Can Anything Else Go Wrong? Can anything go wrong in addition to ArithmeticException? public class SimpleExprThrows { public static int expr(int d1, int d2, String operator) throws ArithmeticException { int result = 0; switch(operator) { case "+": result = d1 + d2; break; case "-": result = d1 - d2; break; case "*": result = d1 * d2; break; case "/": result = d1 / d2; return result; 3/28/2018 CUNY Brooklyn College 31

Can Anything Else Go Wrong? How about we do this? What s wrong? $ java SimpleExpr 2 ^ 3 2^3=0 public class SimpleExprThrows { public static int expr(int d1, int d2, String operator) throws ArithmeticException { int result = 0; switch(operator) { case "+": result = d1 + d2; break; case "-": result = d1 - d2; break; case "*": result = d1 * d2; break; case "/": result = d1 / d2; return result; 3/28/2018 CUNY Brooklyn College 32

Raise an Exception: Example public class SimpleExprThrows { public static void main(string[] args) {... try { result = expr(d1, d2, args[1]); System.out.println(d1 + args[1] + d2 + "=" + result); catch(arithmeticexception e) { System.out.println("The divisor is 0."); catch(illegalargumentexception e) { System.out.println(e.getMessage()); public static int expr(int d1, int d2, String operator) throws ArithmeticException, IllegalArgumentException { int result = 0; switch(operator) { case "+": result = d1 + d2; break; case "-": result = d1 - d2; break; case "*": result = d1 * d2; break; case "/": result = d1 / d2; break; default: throw new IllegalArgumentException("Operator " + operator + " is not supported."); return result; 3/28/2018 CUNY Brooklyn College 33

Commonly Reused Exceptions Use of standard exceptions are generally preferred (Bloch, J., 2008) Exception IllegalArgumentException Occasion for Use Non-null parameter value is inappropriate IllegalStateException NullPointerException IndexOutOfBoundsException ConcurrentModificationException UnsupportedOperationException Object state is inappropriate for method invocation Parameter value is null where prohibited Index parameter value is out of range Concurrent modification of an object has been detected where it is prohibited Object does not support method 3/28/2018 CUNY Brooklyn College 34

Customize an Exception: Example public class SimpleExprThrows { public static void main(string[] args) {... try { result = expr(d1, d2, args[1]); System.out.println(d1 + args[1] + d2 + "=" + result); catch(arithmeticexception e) { System.out.println("The divisor is 0."); catch(illegalargumentexception e) { System.out.println(e.getMessage()); public static int expr(int d1, int d2, String operator) throws ArithmeticException, IllegalArgumentException { int result = 0; switch(operator) { case "+": result = d1 + d2; break; case "-": result = d1 - d2; break; case "*": result = d1 * d2; break; case "/": try { result = d1 / d2; catch (ArithmetricException e) { throw new ArithmeticException("Attempt to evaluate " + d1 + "/" + d2); break; default: throw new IllegalArgumentException("Operator " + operator + " is not supported."); return result; 3/28/2018 CUNY Brooklyn College 35

Subtype an Exception You may extends an Exception class Example public class SimpleExprException extends RuntimeException { SimpleExprException(String msg) { super(msg); 3/28/2018 CUNY Brooklyn College 36

Questions Raise exception Customer exception Create new types of exception 3/28/2018 CUNY Brooklyn College 37

Some Best Practices Do throw specific Exceptions throw new RunTimeException( Exception at runtime ); Throw early, catch late. better to throw a checked exception than to handle the exception poorly. Use exception only for exception situations if (args.length!= 3) { System.out.println( Usage ); try { d1 = Integer.parseInt(args[2]); catch (ArrayIndexOutOfBoundsException e) { System.out.println( Usage ); 3/28/2018 CUNY Brooklyn College 38

Questions Murphy s law Anything that can go wrong will go wrong. Exceptions Catch exceptions (try/catch) Specify requirement for methods (throws) Declare and throw exceptions (throw) Checked and unchecked exception Some Best Practice 3/28/2018 CUNY Brooklyn College 39

Assignment Practice Assignment 3/28/2018 CUNY Brooklyn College 40