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

Similar documents
COMP1008 Exceptions. Runtime Error

C16b: Exception Handling

ECE 122. Engineering Problem Solving with Java

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

Correctness and Robustness

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

BBM 102 Introduction to Programming II Spring Exceptions

Programming II (CS300)

Download link: Java Exception Handling

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

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Exceptions Handling Errors using Exceptions

COMP-202 Unit 9: Exceptions

Programming II (CS300)

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

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

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

ITI Introduction to Computing II

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

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

ITI Introduction to Computing II

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

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

BBM 102 Introduction to Programming II Spring 2017

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

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

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

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

Exception-Handling Overview

Fundamentals of Object Oriented Programming

Internal Classes and Exceptions

What can go wrong in a Java program while running?

Assertions and Exceptions Lecture 11 Fall 2005

Programming Languages and Techniques (CIS120)

Exceptions. CSC207 Winter 2017

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

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

CS193j, Stanford Handout #25. Exceptions

COMP-202 Unit 9: Exceptions

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

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

Errors and Exceptions

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

More on Exception Handling

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

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

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

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

CSCI 261 Computer Science II

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

CSE 331 Software Design & Implementation

Chapter 12 Exception Handling

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

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

CS 3 Introduction to Software Engineering. 3: Exceptions

Topic 5: Abstract Classes & Interfaces

More on Exception Handling

Exceptions - Example. Exceptions - Example

Introduction to Software Design

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

CS159. Nathan Sprague

Exceptions and Design

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

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

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

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

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

Defensive Programming. Ric Glassey

Contents. I Introductory Examples. Topic 06 -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

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

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

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

Chapter 13 Exception Handling

Checked and Unchecked Exceptions in Java

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

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

14. Exception Handling

Chapter 14. Exception Handling and Event Handling ISBN

What are Exceptions?

Programming Languages and Techniques (CIS120)

Full file at Chapter 2 - Inheritance and Exception Handling

Programming - 2. Common Errors

Data Structures. 02 Exception Handling

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

Java Errors and Exceptions. Because Murphy s Law never fails

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


Exceptions and Error Handling

Introduction to Computer Science II CS S-22 Exceptions

Object Oriented Programming Exception Handling

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

Stacks and Queues. Gregory D. Weber. CSCI C243 Data Structures

CS112 Lecture: Exceptions and Assertions

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

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

Transcription:

Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write code that throws exceptions create your own exception types 1

Quote From Java Tutorial "If there's a golden rule of programming it's this: Errors occur in software programs. This we know. But what really matters is what happens after the error occurs. How is the error handled? Who handles it? Can the program recover, or should it just die?" 2

Exceptions Exception: alarm going off when something unusual happens Usually an error (divide by zero, file not found) Sometimes unusual, but not erroneous (example: end of file) Advantages of using exceptions: separate normal code from error-handling code lets you defer decision about how to handle error up the call stack provides hierarchy of errors 3

Exception Class In Java, almost everything is an object An exception is an object of class Exception contains information about what happened, where it happened, and program state at the time most is for Java VM, not programmer What's important for the programmer: what kind of exception is it? the message inside (a String) 4

Exception Classes And many, many more... 5

Exception Messages an exception object contains a message (type String) The message describes the error/unusual circumstance Unfortunately: API documentation often doesn't tell you what will be in messages for different Exception classes... Good practice: When you throw an exception, include a message describing what happened. Program can display the message to the user. Also useful to programmer if program aborts. 6

Example: NumberFormatException to convert a String to an int: int i = Integer.parseInt(s); if s is not in int format, this call throws a NumberFormatException How did I know that? Says so in API documentation for the method When you write a method that can throw an exception, ***document it in the method's header comment! (What kind of exception and under what circumstances.) demo... 7

try { <code that might throw a NumberFormatException> catch (NumberFormatException e) { <code to execute if you get a NumberFormatException> add a try/catch to demo... Catching An Exception 8

Letting Exceptions Propagate Up You don't have to catch an exception in the same method as it was thrown Demo program: CatchDemo main domath getnumber parseint Number Format Exception 9

Multiple Catches try { // code that might throw exceptions catch (ArithmeticException e) { System.out.println("arithmetic exception"); catch (NumberFormatException e) { System.out.println("number format exception"); catch (NullPointerException e) { System.out.println("null pointer exception"); catch (RuntimeException e) { System.out.println("some other runtime exception"); Java tries each catch in order until it finds a match No match exception propagates outwards and up the call stack 10

Order is Important! try { // code that might throw exceptions catch (ArithmeticException e) { System.out.println("arithmetic exception"); catch (RuntimeException e) { // superclass of other 2 System.out.println("some other runtime exception"); catch (NumberFormatException e) { System.out.println("number format exception"); if try code throws NumberFormatException: caught by second catch Third catch clause is unreachable 11

Throw Statement to throw an exception on purpose: throw <exception object>; Exceptions have two constructors: new Exception() // no message new Exception("explanation of error") All Exception subclasses in API have similar constructors usually create and throw in one statement: throw new ArithmeticException(); throw new IOException("file input.txt"); 12

Old Quiz Question try { for (int i = 0; i < 10; i++) { try { if (i == 3) throw new NullPointerException(); if (i == 6) throw new ArithmeticException(); System.out.print(i + " "); // end try catch (NullPointerException e) { System.out.print("null "); // end catch // end for // end try catch (ArithmeticException e) { System.out.print("arithmetic "); // end catch System.out.println("done"); 13

"Throws" Clause When a method may throw an exception, should use a "throws" clause in header void write(int b) throws IOException {... Informs compiler that call of method may cause exception Also good documentation for reader. Also document exceptions in method headers: /***************************************** * This method does blah, blah, blah * Parameters: * a:... * b:... * Return value:... * Exceptions: throws IOException if input file * does not exist ****************************************/ 14

"Catch or Specify" Rule Two ways to write code that can throw an exception: use a "throw" statement call a method that can throw an exception You must do one of the following: catch the exception inside that same method specify that the method may throw an exception (i.e. add a "throws" clause) If you do neither, you get a compiler error 15

Loophole for RuntimeException Special case: if method throws a RuntimeException (or subclass of RuntimeException) don't have to use throws clause ("unchecked exceptions") All other exceptions: throws clause required. ("checked exceptions") Rationale: RuntimeException is for common runtime errors, many methods might throw (divide by zero, null pointer, array index, etc.) Don't document obvious RuntimeExceptions that may be caused by bugs in code (divide by zero, null pointer, etc.) Do document runtime exceptions such as NumberFormatException which may reflect error in input 16

Stack Example recall error conditions in stacks: pop from empty stack push onto full stack for ArrayStack Example code aborted program Better option: raise an exception Advantage: caller can decide what to do public int pop() throws Exception { if (topindex == -1) { throw new Exception("empty stack"); int result = elements[topindex]; topindex--; return result; // end pop 17

Improvement Previous example is OK, but not ideal Caller must catch all exceptions & test message. Better way: declare own exception type. Catch block can catch stack exceptions specifically public class EmptyStackException extends Exception { public EmptyStackException(String msg) { super(msg); // end constructor public EmptyStackException() { super(); // or use a default message // end constructor // end EmptyStackException 18

Organizing Stack Exceptions Create another exception class for adding to a full stack: FullStackException Make both exception classes subclasses of a general class: StackException StackException EmptyStackException FullStackException Advantage: can catch all stack-related exceptions together: catch (StackException e) 19

Modified Stack Interface public interface Stack { public void push(int value) throws FullStackException; public int pop() throws EmptyStackException; public boolean isempty(); 20

Modified pop from ArrayStack public int pop() throws EmptyStackException { if (topindex == -1) { throw new EmptyStackException( "attempt to pop from empty array stack"); int result = elements[topindex]; topindex--; return result; // end pop 21

How to Use Stacks With Exceptions (1) Simplest case: You believe your code will never make a stack error, and/or you don't care if the program aborts when there's an error Surround all stack code with a try/catch, catch will abort: try { Stack s = new LinkedStack();... use s... catch (StackException e) { System.out.println("Stack error: " + e.getmessage()); System.exit(1); ; 22

How to Use Stacks With Exceptions (2) Exceptions give you the flexibility to recover from errors try { teststack.push("new stack element"); catch (FullStackException e) { System.out.println( "Error: stack is full; couldn't push"); // end catch // Program continues, even if error occurred 23

Consequences of Exceptions Now Stack methods can throw exceptions. Calling methods must deal with them: catch them or have "throws" clause Suppose method m pops something off a stack method m must do one of these things: 1. put the pop in a try block with a catch for EmptyStackException 2. include throws EmptyStackException in its header Consequence of #2: all methods that call m must in turn deal with the possible exception (catch or specify) 24

Is This a Bad Thing? Usually, no! At first, seems like a nuisance. But forces programmer to deal with the possibility of an empty stack error Program will be more robust. 25

Occasional Nuisances Consider this code: Stack s;... while (!s.isempty()) { int value = s.pop(); // do something with value // end while This code will never cause an EmptyStackException. But the compiler doesn't know this We must still write code to catch the exception. 26

Provide trivial handler: Solution try { Stack s = new LinkedStack(); // code that pushes integers onto s while (!s.isempty()) { int value = s.pop(); // do something with value // end while catch (EmptyStackException e) { System.out.println("Internal Error: " + + "empty stack in <method name>"); System.exit(1); 27

Temptation: RuntimeException We defined stack exceptions as direct subclasses of Exception. So they are "checked exceptions" must catch or specify. We could have defined them as subclasses of RuntimeException. Then we can ignore them, compiler won't complain. This is legal Java, but bad style. Leave RuntimeException for common runtime errors 28

Exceptions Are For Exceptional Cases public int arraysum(int arr[]) { int sum = 0; try { int i = 0; while (true) { sum += arr[i]; i++; // end while // end try catch (ArrayIndexOutOfBoundsException e) { System.out.println("sum = " + sum); // end catch // end arraysum Bad idea!!! Use loop condition instead: more efficient and more readable. Don't rely on exceptions when there's a simpler way to prevent or detect a problem. 29

Another Practice Problem public static void main(string args[]) { try { practice("124"); System.out.println("124 done"); practice("2468"); System.out.println("2468 done"); practice("35"); System.out.println("35 done"); practice("seventeen"); System.out.println("seventeen done"); practice("twenty5"); System.out.println("twenty5 done"); catch (NumberFormatException e) { System.out.println("format"); // end main public static void practice(string numstring) { int x = 0; try { x = Integer.parseInt(numString); endofterm(x); if (x % 2 == 0) // x is even System.out.println("even " + x); else throw new ArithmeticException(); catch (ArithmeticException e) { System.out.println("arith " + x); catch (NullPointerException e) { System.out.println("null pointer " + x); // end practice public static void endofterm(int number) { if (number > 200) throw new NullPointerException(); System.out.println("good " + number); // end endofterm 30