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

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

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

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

CS159. Nathan Sprague

Exceptions - Example. Exceptions - Example

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

BBM 102 Introduction to Programming II Spring Exceptions

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

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

COMP1008 Exceptions. Runtime Error

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

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:

BBM 102 Introduction to Programming II Spring 2017

ITI Introduction to Computing II

Exception-Handling Overview

CS159. Nathan Sprague

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

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

C16b: Exception Handling

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

CSCI 261 Computer Science II

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

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

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

CS 3 Introduction to Software Engineering. 3: Exceptions

COMP-202 Unit 9: Exceptions

Exceptions in Java

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

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

Correctness and Robustness

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

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

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

Introductory Programming Exceptions and I/O: sections

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

CSE 331 Software Design & Implementation

Data Structures. 02 Exception Handling

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

Fundamentals of Object Oriented Programming

COMP-202 Unit 9: Exceptions

Sri Vidya College of Engineering & Technology Question Bank

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

CS112 Lecture: Exceptions and Assertions

Full file at Chapter 2 - Inheritance and Exception Handling

EXCEPTIONS. Java Programming

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

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

Comp 249 Programming Methodology Chapter 9 Exception Handling

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

Exceptions and Design

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

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

Intro to Computer Science II. Exceptions

Exceptions and Libraries

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Lesson 3: Accepting User Input and Using Different Methods for Output

Recitation 3. 2D Arrays, Exceptions

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

More Control Structures

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

Exception Handling CSCI 201 Principles of Software Development

Exceptions and Error Handling

What can go wrong in a Java program while running?

For more details on SUN Certifications, visit

What are Exceptions?

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

Programming Languages and Techniques (CIS120)

Chapter 13 Exception Handling

Defensive Programming. Ric Glassey

More on Exception Handling

Programming II (CS300)

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

CS193j, Stanford Handout #25. Exceptions

EXCEPTION HANDLING. Summer 2018

Programming - 2. Common Errors

Programming II (CS300)

Exception Handling Generics. Amit Gupta

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

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

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

Object Oriented Programming Exception Handling

Java Exceptions Version June 2009

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Points To Remember for SCJP

Object Oriented Programming

CS 209 Programming in Java #10 Exception Handling

EXCEPTIONS. Fundamentals of Computer Science I

More on Exception Handling

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

Object Oriented Programming

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Transcription:

Introduction to Computation and Problem Solving Class 25: Error Handling in Java Prof. Steven R. Lerman and Dr. V. Judson Harward Goals In this session we are going to explore better and worse ways to handle errors. In particular, we are going to learn about the exception mechanism in Java. After learning about exceptions, you are going to rework a specialized editor application to make the error handling more user friendly and effective. 2 1

3 Approaches to Error Handling The error code The error flag in memory, cf. UNIX errno Exceptions the ejector seat 3 Using Error Codes public static double average( double [] darray ) if ( darray.length == 0 ) return???; double sum = 0.0; for ( int i = 0; i < darray.length; i++ ) sum += darray[ i ]; return sum / darray.length; 4 2

Using Error Codes, 2 You can return Double.NaN. You must test it as follows: double[] darray = ; double d = average( darray ); if ( Double.isNaN( d ) ) // error else // OK 5 Using an Error Flag public class MyMath static public final int ILLEGAL_ARGUMENT = -1; static public int errflag = 0; public static double average( double [] darray ) if ( darray.length == 0 ) errflag = ILLEGAL_ARGUMENT; return???; double sum = 0.0; for ( int i = 0; i < darray.length; i++ ) sum += darray[ i ]; return sum / darray.length; 6 3

Using Exceptions Advantages: Can not be confused with a normal return. Programmer has to work to ignore it. Error can be dealt with anywhere (up the call stack). Error conditions can be intelligently grouped using a variation of inheritance. Now for the mechanism: 7 Throwing an Exception public static double average( double [] darray ) throws IllegalArgumentException if ( darray.length == 0 ) throw new IllegalArgumentException(); double sum = 0.0; for ( int i = 0; i < darray.length; i++ ) sum += darray[ i ]; return sum / darray.length; 8 4

Declaring an Exception If a method can throw an exception, you can always declare the type of the exception in the header after the keyword throws public static double average( double [] darray ) throws IllegalArgumentException The compiler requires you to declare the possible exception throw if the exception class is not derived from RuntimeException or Error. These are called checked exceptions (checked by the compiler). Exceptions derived from RuntimeException or Error are called unchecked exceptions and their declaration is optional. IllegalArgumentException is actually unchecked. 9 Checked vs. Unchecked Exceptions The distinction between checked and unchecked exceptions is fairly arbitrary. In principle, checked exceptions are those which you, the programmer, are supposed to be able to fix at runtime, such as a FileNotFoundException. Very often these are generated in system code by user, not programmer, error. Unchecked exceptions are supposed to be able to occur anywhere (so hard to check for) and to be the result of programmer error (so the best way of handling them is to fix the program). Good examples, NullPointerException, ArrayIndexOutOfBoundsException. Bad example, NumberFormatException, thrown e.g. by Integer.parseInt(String s). 10 5

Creating Exception Instances Exceptions are objects. You must create a new instance of an exception before you can throw it if ( darray.length == 0 ) throw new IllegalArgumentException(); Exceptions can be arbitrarily complex, but the exceptions supplied with the JDK possess a default constructor and a constructor that takes a single error message string. 11 Catching Exceptions Normal execution of a method ceases at the point an exception is thrown. The runtime environment then looks for an enclosing try block with a matching catch clause. After executing the catch clause, the program resumes with the first statement after the catch block. 12 6

throw/try/catch Pattern try if ( error ) throw new MyException(); //skip futher execution catch ( MyException e ) // handle exception e catch( MyException2 e )... // optional... finally // optional... // always executed if present //resume execution 13 Catching Exceptions, 2 If there is no enclosing try block in the current method, or one with an appropriately typed catch clause, then the Java Virtual Machine goes hunting up the call stack for a matching try/catch pair. If the JVM can't find such a pair on the call stack, the default behavior is to print out an error message and halt the thread (the whole program if a console app; otherwise the program "hangs" ). 14 7

Catching Exception Up the Call Stack double [] mydoubles =... ; double a = 0.0; try a = average( mydoubles ); catch ( IllegalArgumentException e ) // do something about it System.out.println( Average = + a ); 15 Not Catching Exception Up the Call Stack import javax.swing.*; public class BadArgument public static void main( String [] args ) while ( true ) String answer = JOptionPane.showInputDialog( "Enter an integer" ); int intanswer = Integer.parseInt( answer ); // What happens if the user types %!Z$ if ( intanswer == 42 ) break; System.exit( 0 ); 16 8

Better BadArgument Implementation public class BadArgument public static void main( String [] args ) while ( true ) String answer = JOptionPane.showInputDialog( "Enter an integer" ); int intanswer; try intanswer = Integer.parseInt( answer ); catch ( NumberFormatException e ) JOptionPane.showMessageDialog( null, "Not an integer" ); if ( intanswer == 42 ) break; System.exit( 0 ); 17 Writing Your Own Exception Classes Writing your own exception class is simple. New exception classes allow you to handle a new type of error separately. Exception classes extend java.lang.exception. public class DataFormatException extends java.lang.exception public DataFormatException() super(); public DataFormatException(String s) super( s ); 18 9

What an Exception Object Contains All Exception objects implement a tostring() method that will print out the exception type and the exception message, if any. You can also retrieve the error message (the String argument, if present) by using the method: public String getmessage() 19 Exceptions and Error Handling The Zen of error handling starts with the realization that the place you discover an error is almost never the place where you can fix it. Older languages like C use the horrible kludge of error codes and flags as we have seen. C++ introduced exceptions into the C family. But many programmers simply don t test for errors. 20 10

The Exception Strategy The goal of using exceptions is to split the problem of detecting errors from the problem of handling them. 21 Exceptions in the Calculator From CalculatorController:doOp() try... switch( et ) case Calculator.I_DIV: setacc( model.div() ); break;... catch ( EmptyStackException e ) error(); 22 11

Exceptions in the Calculator, 2 Where does the exception get thrown? Not in CalculatorModel. public double div() throws EmptyStackException double bot = stack.pop(); double top = stack.pop(); return top / bot; 23 Exceptions in the Calculator, 3 CalculatorController: public double doop() does and puts FSM in ERROR state CalculatorModel: public double div() doesn t catch it! ArrayStack<E>: public E pop() throws EmptyStackException 24 12

Exceptions in the Calculator, 4 Despite the fact that EmptyStackException is an unchecked exception, it is caused here by user error (not entering enough operands) not programmer error. ArrayStack doesn't know how to fix it so it throws it. CalculatorModel doesn't know how to fix it, so it throws it. Finally, CalculatorController can do something about it so it catches the exception and puts the whole calculator into the Error state until the user clears it. 25 Exceptions and Inheritance Since exceptions are instances of classes, exception classes may use inheritance. A FileNotFoundException is a derived class of IOException. When an error is detected, you should create and throw a new instance of an appropriate type of exception. The stack is searched for the nearest catch statement matching the exception class or one of its superclasses. 26 13

Exception Inheritance Example try FileReader in = new FileReader( "MyFile.txt" ); // read file here catch ( FileNotFoundException e ) // handle not finding the file (bad file name?) catch ( IOException e ) // handle any other read error 27 BirthdayApp Exercise, 1 Download Lecture25.zip from the class web site. These files implement a birthday list editor. Examine the classes in the 3 files: BirthdayApp: This is the application class with the main() method. BirthdayView: This is the combined view and controller class. BirthdayModel: This class maintains the growing list of birthdays. Don't worry about the methods labelled "Related to MVC" towards the end of the file. They update the JList when a new birthday is added. Birthday: contains the name and date information. 28 14

BirthdayApp Exercise, 2 Compile these classes and run the main method of BirthdayApp. This will open a window on the screen that contains a single birthday and a button. Click the button. This will prompt you to enter a name. Enter your name. Next, it will prompt you to enter the date of your birthday,enter the following exactly: January 1, 2002 You should see that your name and January 1, 2002 have been added to the list of Birthdays. Click the button again. This time, enter a name and the following exactly: january 1, 2002 You should see that the program has exited completely. Why did this happen? Examine the addbirthday() method in the BirthdayModel class closely. You should see that if the addbirthday() method has any trouble parsing the String bdaydate, it invokes System.exit(). Your first goal in this active learning session is to modify addbirthday() so that it does not call System.exit(). Instead, it should throw an exception when it cannot correctly parse the String bdaydate. 29 BirthdayApp Exercise, 3 Your second goal in this active learning session is to modify the actionperformed() method in the BirthdayView class so that it can react to exceptions thrown by addbirthday(). When you are completely done with the program, your final solution should take input from the user in exactly the same way. However, when the user enters something wrong, the program should not quit. Instead, it should tell the user that they did something wrong. Make your error handling as useful as possible. Try and let the user know not only that an error has occurred but give him or her a chance to fix it. 30 15