CSCI 261 Computer Science II

Similar documents
CS159. Nathan Sprague

BBM 102 Introduction to Programming II Spring Exceptions

ECE 122. Engineering Problem Solving with Java

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

BBM 102 Introduction to Programming II Spring 2017

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

Exceptions - Example. Exceptions - Example

Exception-Handling Overview

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

C16b: Exception Handling

Chapter 12 Exception Handling

Lecture 19 Programming Exceptions CSE11 Fall 2013

Programming II (CS300)

CS159. Nathan Sprague

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

More on Exception Handling

More on Exception Handling

Programming II (CS300)

Exceptions. CSC207 Winter 2017

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

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

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

ITI Introduction to Computing II

ITI Introduction to Computing II

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

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

Java Exception. Wang Yang

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Errors and Exceptions

Chapter 13 Exception Handling

Fundamentals of Object Oriented Programming

Data Structures. 02 Exception Handling

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

COMP-202 Unit 9: Exceptions

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

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Object Oriented Programming

What can go wrong in a Java program while running?

EXCEPTION HANDLING. Summer 2018

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

COMP-202 Unit 9: Exceptions

Object Oriented Programming Exception Handling

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Java Errors and Exceptions. Because Murphy s Law never fails

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

CS 11 java track: lecture 3

Correctness and Robustness

CS 3 Introduction to Software Engineering. 3: Exceptions

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

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

16-Dec-10. Consider the following method:

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

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

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

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

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

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

Exceptions and Libraries

6.Introducing Classes 9. Exceptions

Computer Science is...

Typecasts and Dynamic Dispatch. Dynamic dispatch

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

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

CSE 143 Java. Exceptions 1/25/

Exceptions and Error Handling

Recitation 3. 2D Arrays, Exceptions

Internal Classes and Exceptions

COMP1008 Exceptions. Runtime Error

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 to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

Introduction Unit 4: Input, output and exceptions

Exception Handling CSCI 201 Principles of Software Development

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

Designing Robust Classes

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

Introductory Programming Exceptions and I/O: sections

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

Exceptions and assertions

Motivations. Chapter 12 Exceptions and File Input/Output

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

For more details on SUN Certifications, visit

CSE 331 Software Design & Implementation

Writing your own Exceptions. How to extend Exception

Program Correctness and Efficiency. Chapter 2

Defensive Programming

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

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

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

Introduction to Computer Science II CS S-22 Exceptions

CSC 1214: Object-Oriented Programming

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

EXCEPTIONS. Fundamentals of Computer Science I

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

Intro to Computer Science II. Exceptions

Full file at Chapter 2 - Inheritance and Exception Handling

Video 2.1. Arvind Bhusnurmath. Property of Penn Engineering, Arvind Bhusnurmath. SD1x-2 1

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

Transcription:

CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling

New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design - Class hierarchy, class diagrams (UML) - Inheritance and polymorphism - Abstract classes and interface Now Change in pace: Handling Java runtime errors (exceptions) - Why wait until now? Needed to understand inheritance first Exceptions also follow a class hierarchy Keywords in this lecture: throw, throws, try, catch 2

Runtime Errors Happen When running a program, it sometimes result in exceptions Maybe people didn't bother reading your comments - Pro tip: Read the API before diving into code! Maybe it was a simple logic mistake - Dreaded 1-off errors, divide by zero, etc. Maybe it was an external factor - Opening a file that doesn't exist, or you don't have permission 3

Exceptions You've seen exceptions at some point Divide by zero: int x = 4; x /= 0; Exception: java.lang.arithmeticexception (/ by zero) Out of bounds access: int[] list = {10, 20, 30; System.out.println(list[3]); Exception: java.lang.arrayindexoutofboundsexception (3) 4

Exceptions (Cont.) More you've probably seen: Following a null reference: Triangle t1, t2; double sum = t1.getarea() + t2.getarea(); Exception: NullPointerException: t1 Illegal input to a method/constructor: int x = Integer.parseInt("david"); Exception: java.lang.numberformatexception (For input string: "david") What about... making our own? (Later) Shape s = new Rectangle(0, 0, -4, 5); //a -4 x 5 rectangle located at the origin? 5

Outline What Are Exceptions? How Exceptions Work Exception Handling Receiving end: throws clause and try-catch block Producing end: throwing exceptions Exception Types: Unchecked vs. Checked Defining Custom Exceptions Conclusion 6

How Exceptions Work When an exception is raised (or thrown), your program terminates! Maybe that's okay (whatevs... it's just students using my program) Maybe that's unacceptable (published software) More graceful approaches to handling exceptions? Report the error and its likely cause Try to recover (not always possible): - Maybe we could just keep asking for a better input? 7

How Exceptions Work (Cont.) Operative terms Throwing (or raising) an exception - Complain about an error Catching an exception elsewhere in code - Checks for existence of an exception and "handling" it somehow - try-catch clause (more on this later) In Java, exceptions are objects being thrown and caught 8

Exception Handling Like Game of "Hot Potato" 9

How Exceptions Work (Cont.) Mechanism for exception handling: An exception gets "thrown up" the call stack Terminate program! Java Virtual Machine (JVM) After exception is thrown, main() Java searches each call for willingness to handle it - If the method "catches" and handles it: A() Great, exception goes away! - If the method is not willing to handle it It gets thrown up to its caller method If no one handles it, the exception reaches the JVM, which terminates the program B() C()!!! Call Stack 10

How Exceptions Work (Cont.) Take a second to read this code: 11 public static void main(string[] args) { 12 Scanner keyboard = new Scanner(System.in); 13 int x = keyboard.nextint(); //assume they enter "0" 14 int y = foo(x); 15 16 17 public static int foo(int z) { 18 return 10 / z; 19 Here's the exception reported by the JVM: Call Stack java.lang.arithmeticexception: / by zero at Testing.foo(Testing.java:18) at Testing.main(Testing.java:14) Exception originated here in foo() Called by main() But main() didn't "handle" it, so it reaches JVM 11

Outline What Are Exceptions? How Exceptions Work Exception Handling Receiving end: throws clause and try-catch block Producing end: throwing exceptions Exception Types: Unchecked vs. Checked Defining Custom Exceptions Conclusion 12

Exception Handling (Option 1) A method has two options when it receives an exception: Option 1: Play hot potato. (Throw it up to caller) - Syntax: <method declaration> throws exceptiontype0, exceptiontype1,... Example: /** * @return A foo number * @throws ArithmeticException if z is zero */ public static int foo(int z) throws ArithmeticException { return 10 / z; Note the following: A new @throws tag for Javadocs commenting 13

Exception Handling (Option 2) Option 2: Try to survive the exception Syntax: - Syntax of try-catch block directly within the method body Need to have a plan to recover the program from crashing - Could have multiple catch statements per try-clause Multiple exceptions could be thrown in a block of code try { //code that could result in exception catch(exceptiontype e0) { //what to do if one type of exception was thrown in try-block? catch(exceptiontype e1) { //what to do if a different type exception was thrown? //maybe more 14

Example Handling the exception in foo(..) public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); int x = keyboard.nextint(); //assume they enter "0" int y = foo(x); public static int foo(int z) { try { // This is the "dangerous" statement return 10 / z; catch(arithmeticexception ex) { System.out.println(ex.getMessage()); //what was the error? return -1; 15

Example Could also handle the exception in main(..) public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); int x = keyboard.nextint(); //assume they enter "0" int y; try { // This is the "dangerous" statement y = foo(x); catch(arithmeticexception ex) { System.out.println(ex.getMessage()); //what was the error? y = -1; public static int foo(int z) throws ArithmeticException { return 10 / z; 16

Outline What Are Exceptions? How Exceptions Work Exception Handling Receiving end: throws clause and try-catch block Producing end: throwing exceptions Exception Types: Unchecked vs. Checked Defining Custom Exceptions Conclusion 17

Throwing Exceptions So far, we've only seen exceptions being generated automatically What if we wanted to throw our own exceptions? Syntax (in the body of the method): Note: Not to be confused with the throws keyword we just saw previously Note: the new keyword indicates that Exceptions are objects in Java public void somemethod() {... if (somethingwentwrong) { throw new ExceptionType("optional diagnostic message"); 18

Example: Throwing Our Own Exceptions Example: What could go wrong with the following code? /** * Doubles the size of a rectangle * @param r A reference to a Rectangle */ public void enlarge(rectangle r) { r.setwidth(r.getwidth() * 2); r.setlength(r.getlength() * 2); 19

Example (Cont.) What could go wrong? Could potentially follow a null reference! Let's inform callers of this potential problem: /** * Doubles the size of a rectangle * @param r A reference to a Rectangle * @throws IllegalArgumentException when null is given */ public void enlarge(rectangle r) { if (r == null) { throw new IllegalArgumentException("null given in enlarge()"); r.setwidth(r.getwidth() * 2); r.setlength(r.getlength() * 2); Important: Wouldn't these still run after the Exception was thrown? No, throw has an added effect of method termination (like return) 20

Exceptional Execution Call foo() public void foo() { Rectangle r; try { enlarge(r); catch(illegalargumentexception ex) { System.out.println(ex.getMessage()); //more code blah blah Rectangle r; enlarge(r); false r == null? true In foo() In enlarge() public void enlarge(rectangle r) { if (r == null) { throw new IllegalArgumentException("null reference given in enlarge()"); r.setwidth(r.getwidth() * 2); r.setlength(r.getlength() * 2); r.setwidth(..) r.setlength(..) throw new IllegalArgument.. Exit immediately S.o.pln(ex.getMessage()) more code (blah blah) catch statement(s) 21

Outline What Are Exceptions? How Exceptions Work Exception Handling Receiving end: throws clause and try-catch block Producing end: throwing exceptions Exception Types: Unchecked vs. Checked Defining Custom Exceptions Conclusion 22

Exception Hierarchy Exceptions have an inheritance hierarchy in Java We can create new exceptions by extending the Exception class Error vs. Exceptions - Error: unrecoverable errors. Don't try to catch; let program fail e.g., out of memory, stack overflow - Exception: errors the programmer has control over Throwable Error Exception RuntimeException other checked Exceptions other unchecked Exceptions 23

Throwable API Full API here: https://docs.oracle.com/javase/8/docs/api/java/lang/throwable.html Signature public Throwable() Descrip.on Constructs a new throwable with null as its detail message. public Throwable(String message) Constructs a new throwable with the specified detail message. public String getmessage() Returns the detail message string of this throwable. public void printstacktrace() Prints this throwable and its backtrace to the standard error stream. public String tostring() Returns a short descripcon of this throwable. 24

Exception API Full API here: https://docs.oracle.com/javase/8/docs/api/java/lang/exception.html Signature public Exception() public Exception(String message) Descrip.on Constructs a new excepcon with null as its detail message. Constructs a new excepcon with the specified detail message. (Other inherited Throwable methods) 25

Java Has Two Exception Types Unchecked exception: Cases where programmer screwed up e.g., Div by 0, null exception, illegal array access Java says, "Don't have to explicitly warn users about these." - That is, you don't need to write a try-catch clause! - Compiler won't "check" for that! Checked exception: Cases where program-user screwed up e.g., Bad input from keyboard, write file to a full disk Java says, "You must catch and handle." - You must either throw it up, or write a try-catch clause for these! - Compiler will "check" for that to keep you honest! 26

Exception Hierarchy Checked exceptions should extend the Exception class Unchecked exceptions should extend the RuntimeException class Throwable Error Exception MyCheckedException RuntimeException other checked Exceptions MyUncheckedException other unchecked Exceptions 27

Example 1 Check out IllegalArgumentException documentation Is it checked or unchecked? The compiler lets this go: Well, enlarge() might throw an unchecked exception, but whatevs... \_( ツ )_/ public void foo() { Rectangle r; enlarge(r); //more code blah blah Unchecked means unrecoverable, so program's gonna die soon anyway public void enlarge(rectangle r) { if (r == null) { throw new IllegalArgumentException("null given in enlarge()"); r.setwidth(r.getwidth() * 2); r.setlength(r.getlength() * 2); 28

Example 1 (Cont.) Check out IllegalArgumentException documentation Is it checked or unchecked? The compiler lets this go: Method does not need to indicate that it throws unchecked exceptions! public void foo() { Rectangle r; enlarge(r); //more code blah blah public void enlarge(rectangle r) { if (r == null) { throw new IllegalArgumentException("null given in enlarge()"); r.setwidth(r.getwidth() * 2); r.setlength(r.getlength() * 2); 29

Example 1 (Cont.) Check out IllegalArgumentException documentation Is it checked or unchecked? The compiler lets this go: But there's nothing wrong with indicating it anyway! (Preferred, actually) public void foo() { Rectangle r; enlarge(r); //more code blah blah public void enlarge(rectangle r) throws IllegalArgumentException { if (r == null) { throw new IllegalArgumentException("null given in enlarge()"); r.setwidth(r.getwidth() * 2); r.setlength(r.getlength() * 2); 30

Example 2 Check out FileNotFoundException documentation Is it checked or unchecked? The compiler won't let this one go: Well, open_file() might throw a checked exception. This could be recoverable... public void foo() { Scanner keyboard = new Scanner(System.in); String file = keyboard.nextline(); //get a filename from the user open_file(file); //... public void open_file(string filename) throws FileNotFoundException { if (filename == null!exists(filename)) { throw new FileNotFoundException("null given in enlarge()"); //code to open file 31

Example 2 (Cont.) Check out FileNotFoundException documentation Is it checked or unchecked? The compiler won't let this one go: Compiler insists that you either throw it up to caller or try-catch it here! public void foo() { Scanner keyboard = new Scanner(System.in); String file = keyboard.nextline(); //get a filename from the user open_file(file); //... public void open_file(string filename) throws FileNotFoundException { if (filename == null!exists(filename)) { throw new FileNotFoundException("null given in enlarge()"); //code to open file 32

Example 2 (Cont.) Check out FileNotFoundException documentation Is it checked or unchecked? The compiler won't let this one go: public void foo() { Scanner keyboard = new Scanner(System.in); String file = keyboard.nextline(); //get a filename from the user open_file(file); //... public void open_file(string filename) throws FileNotFoundException { if (filename == null!exists(filename)) { throw new FileNotFoundException("null given in enlarge()"); Compiler wants //code to open file programmer to know it can be handled without resulting in termination. 33

Take-Home Exercise Peruse Java's documentation on the following exceptions, and determine: When they occur Whether they're checked or unchecked Name When Checked Unchecked IllegalArgumentException Invalid argument received by method. x ArithmeticException Illegal arithmecc operacon detected. x FileNotFoundException AGempCng to access a non-existent file. x IOException ArrayIndexOutOfBoundsException EOFException NullPointerException NumberFormatException 34

Take-Home Exercise (Soln) Name When Checked Unchecked IllegalArgumentException Invalid argument received by method. x ArithmeticException Illegal arithmecc operacon detected. x FileNotFoundException AGempCng to access a non-existent file. x IOException An I/O operacon has failed. (e.g., wricng to a file, reading from scanner,..) x ArrayIndexOutOfBoundsException Self-explanatory x EOFException An "end-of-file" marker has been reached expectedly when reading file or stream. x NullPointerException Self-explanatory x NumberFormatException AGempted to convert a string to one of the numeric types, but that the string does not have the appropriate format x 35

Outline What Are Exceptions? How Exceptions Work Exception Handling Receiving end: throws clause and try-catch block Producing end: throwing exceptions Exception Types: Unchecked vs. Checked Defining Custom Exceptions 36

Defining Our Own Exceptions Note how the names of these exceptions are quite descriptive Sometimes, not descriptive enough We can optionally create our own Exception classes - We get to decide whether our exception needs to be "checked" Let's say we want to throw an IllegalShapeException if a user tries to set its dimensions to invalid values 37

Defining IllegalShapeException /** * An IllegalShapeException is a checked exception that should be thrown whenever * a user attempts to change the dimensions of a shape to illegal value(s). * * @author David * @version 6/8/2017 */ public class IllegalShapeException extends Exception { /** * Creates an IllegalShapeException object */ public IllegalShapeException() { super(); /** * Creates an IllegalShapeException object with a diagnostic note * @param message a diagnostic message */ public IllegalShapeException(String message) { super(message); 38

Circle Class Now public class Circle extends Shape { protected double radius; public Circle(int x, int y, double r) { super(x, y); //call Shape(x,y) this.radius = r; /** * Assigns a new radius. * @param new_radius length of new radius * @throws IllegalShapeException if new radius is not positive */ public void setradius(double new_radius) throws IllegalShapeException { if (new_radius <= 0) { throw new IllegalShapeException("the radius of a circle must be positive: " + new_radius); radius = new_radius; //other methods... 39

Tester (Client Class) public class Tester { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); Circle c = new Circle(0, 0, 5); //a circle at the origin with radius=5 boolean success = false; while (!success) { System.out.print("Input a new radius: "); double new_radius = keyboard.nextdouble(); try { c.setradius(new_radius); success = true; //made it here, that means setradius didn't cause errors catch(illegalshapeexception e) { System.out.println(e.getMessage()); //print out a message warning user System.out.println("radius: " + c.getradius()); Interaction (with exception) Input a new radius: 0 the radius of a circle must be positive: 0.0 Input a new radius: -3 the radius of a circle must be positive: -3.0 Input a new radius: 9 radius: 9.0 Interaction (normal) Input a new radius: 20 radius: 20.0 40

Outline What Are Exceptions? How Exceptions Work Exception Handling Receiving end: throws clause and try-catch block Producing end: throwing exceptions Exception Types: Unchecked vs. Checked Defining Custom Exceptions Conclusion 41

Summary Exceptions are objects representing errors in execution Can be checked or unchecked You can create your own Mechanism is to throw exceptions when error is detected Thrown to the caller method, which has a choice of what to do with it! "I was doing all these defensive programming stuff already!" Yes, but Exceptions can get the compiler involved too If you don't explicitly handle a checked exception, it won't compile 42