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

Similar documents
Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

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

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

CS 3 Introduction to Software Engineering. 3: Exceptions

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

Chapter 13 Exception Handling

COMP1008 Exceptions. Runtime Error

BBM 102 Introduction to Programming II Spring Exceptions

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

BBM 102 Introduction to Programming II Spring 2017

Correctness and Robustness

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

Data Structures. 02 Exception Handling

Lecture 19 Programming Exceptions CSE11 Fall 2013

17. Handling Runtime Problems

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

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

Exceptions. CSC207 Winter 2017

Exceptions. When do we need exception mechanism? When and why use exceptions? The purpose of exceptions

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

Errors and Exceptions

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

Exceptions - Example. Exceptions - Example

Programming Languages and Techniques (CIS120)

Full file at Chapter 2 - Inheritance and Exception Handling

Exception-Handling Overview

Comp 249 Programming Methodology Chapter 9 Exception Handling

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

EXCEPTION HANDLING. Summer 2018

ECE 122. Engineering Problem Solving with Java

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

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

Programming II (CS300)

More on Exception Handling

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

6.Introducing Classes 9. Exceptions

Exceptions and Libraries

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

CS193j, Stanford Handout #25. Exceptions

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

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

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

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

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

ITI Introduction to Computing II

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

More on Exception Handling

C16b: Exception Handling

ITI Introduction to Computing II

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Exceptions Handling Errors using Exceptions

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

EXCEPTIONS. Java Programming

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

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

CSCI 261 Computer Science II

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

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

Chapter 12 Exception Handling

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:

Exception handling in Java. J. Pöial

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

Abstract Classes, Exceptions

Defensive Programming

For more details on SUN Certifications, visit

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

CSE 331 Software Design & Implementation

Object Oriented Programming. Week 7 Part 1 Exceptions

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

Assertions and Exceptions Lecture 11 Fall 2005

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

Binary search. int index = Collections.binarySearch(list, element);

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

COMP-202 Unit 9: Exceptions

Exception Handling. Exception Handling

Exception Handling Generics. Amit Gupta

CS 11 java track: lecture 3

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

2.6 Error, exception and event handling

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

Exceptions and Error Handling

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

Introduction Unit 4: Input, output and exceptions

Java Loose Ends. 11 December 2017 OSU CSE 1

Exception Handling CSCI 201 Principles of Software Development

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

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

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

Class, Variable, Constructor, Object, Method Questions

Object Oriented Programming

Defensive Programming. Ric Glassey

Programming II (CS300)

Projeto de Software / Programação 3 Tratamento de Exceções. Baldoino Fonseca/Márcio Ribeiro

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Chapter 3 Java Exception

Input-Output and Exception Handling

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

Transcription:

Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented Design using Java, by Niño and Hosch» Chapter 21, Introduction to Programming in Java, Dugan Other References» "Handling Errors with Exceptions", Java tutorial» http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 2 Exceptions In the old days, error conditions were usually handled with returned error codes If function really returns a value, can have problems distinguishing between error condition and legitimate value» which value will never, ever occur normally? Exceptions provide a much more elegant way to deal with error conditions! 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 3 Exceptional Conditions An exceptional condition is a problem that prevents the continuation of the method or scope that you re in You can t continue because the current context doesn t have enough information to solve the problem then and there There is no definite rule about what s an exceptional condition and what is not. Use common sense! 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 4

Define common sense: return value,... If the problem is something that might happen quite often in perfectly good code, then a distinguished return value might suffice» BufferedReader readline() returns a String containing the contents of the line or returns null if the end of the stream has been reached» ArrayList indexof(object elem) returns the index of the first occurrence of the argument in the list or returns -1 if the object is not found, checked exception,... If the problem is something that might happen from time to time (but not often) in well written code, you can use a checked exception» the compiler checks that all checked exceptions are caught by error handling code somewhere» FileReader(File f) throws FileNotFoundException if the specified file is not found» InetAddress getbyname(string host) throws UnknownHostException if no IP address for the host could be found 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 5 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 6, runtime exception,... If the problem will not happen in well written code, then you don't need to check for it» subclasses of RuntimeException» ArithmeticException (eg, divide by zero)» NullPointerException (eg, try to access an object method with a null reference)» IndexOutOfBoundsException (eg, attempt to access an array element with an index that is too large or too small), fatal error. Some problems are so bad that the program just has to give up entirely» NoClassDefFoundError - Thrown when JVM tries to load in the definition of a class but no definition of the class can be found» NoSuchMethodError - Thrown if an application tries to call a specified method of a class and that class no longer has a definition of that method. This error can only occur at run time if the definition of a class has incompatibly changed. 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 7 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 8

So, common sense is: return value» you expect this event to occur checked exception» it might occur and you know what to do runtime exception» it might occur, but it's a bug, so the program should exit as gracefully as it can error» we are in deep trouble, and the JVM should terminate the program immediately When to Use Exceptions Exceptions are meant for unexpected error conditions. Exceptions are not meant for simple, expected situations Deciding which situations are expected and which are not is a fuzzy area. If the user is involved, expect the unexpected... Do not use exceptions as a way to report expected situations. They cost more in execution time than a simple if (condition) check. 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 9 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 10 Generating Exceptions All exceptions are generated by constructors and methods A constructor or method declares in its signature which checked exceptions it might throw public BusReader(String host,int port) throws IOException { Socket s = new Socket(host,port); InputStream in = s.getinputstream(); textreader = new BufferedReader(new InputStreamReader(in)); Any method might throw a RuntimeException or Error, regardless of its signature. from BusReader.java 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 11 Handling Exceptions So, you can tell from looking at the javadoc API (or other class documentation that shows method signatures) whether you need to worry about handling exceptions. To handle exceptions, enclose the method invocation in a try/catch block. try { risky business catch (IOException e) { fix it up 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 12

Example finally block try { if (arg.length == 2 && arg[0].tolowercase().equals("file")) { source = new BusReader(arg[1]); else if (arg.length == 3 && arg[0].tolowercase().equals("net")) { int port = Integer.parseInt(arg[2]); source = new BusReader(arg[1],port); else { System.out.println(usage); catch (IOException e) { System.out.println(e); catch (NumberFormatException e) { System.out.println(e); What if there is some code we want to execute whether or not there are problems? Use a finally block after the last catch block try { risky business catch (IOException e) { fix it up finally { always do this from BusDisplay.java 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 13 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 14 We've caught it, now what? What should be done in an exception handler?» Unwind any partially executed state» eg, if first of two files is open but second failed, close the first one» eg, if an ArrayList is allocated, but the mandatory first entry failed, set the list reference to null Details depend on the application.» A dialog box (warning/error)» Write a message to a log that an operation failed» Invoke method System.exit()» Sometimes (rarely), do nothing 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 15 Handling Exceptions If it is not appropriate for your method to handle an exception, simply let it flow upward by adding a throws to your method s signature public void mymethod() throws AnException { amethod(); At some point above you in the calling sequence, the exception will be caught 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 16

What if several Exceptions are possible? What if there are multiple exceptions that could be thrown within a try{ block?» Each exception will need a catch{ that can handle it. The VM will go through the list of catch{ blocks for the try{, and will use the first one that catches the same type of Exception that has been thrown. If you don t provide an appropriate catch{ for each exception that can be thrown or specify that you might throw the exception yourself, you will get a compile error. 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 17 Catching a superclass is okay You are not required to catch the exact Exception subclass that is thrown. You can also catch any superclass of the one that is thrown. So, for example» if FileNotFoundException extends IOException» and FileNotFoundException is thrown» it is permissible to catch either FileNotFoundException or IOException. It is usually advisable to be as specific as you can in what you catch. This encourages more appropriate error handling. 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 18 Try / Catch Summary Execution enters a try{ block If an exception is thrown, execution jumps immediately to the appropriate catch{ block If an exception is not thrown, execution proceeds through the try{ block, then skips all the catch { blocks In either case (exception or not), when execution exits the try{ block, it proceeds to a finally{ block if there is one. ExceptionExample.java 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 19 Exceptions are objects Exceptions in Java are (not surprisingly) defined in classes All such classes inherit from java.lang.throwable 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 20

java.lang.exception Runtime errors that are usually recoverable» It s common to define new ones Must be handled or code will not compile, except for instances of RuntimeException» RuntimeExceptions are like Errors, in that the problem is usually fundamental and potentially serious.» It is possible to catch RuntimeExceptions, but not generally a good idea. Fix the bug instead! java.lang.error Reserved for fundamental, usually serious problems at the VM level Should not be caught--they can occur anywhere, so trying to handle them is impractical.» Usually they are fatal anyway For example: OutOfMemoryError, ClassFormatError, NoClassDefFoundError It is very rare to define new Error subclasses 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 21 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 22 java.lang.throwable In a catch(exception e){, you are passed an instance of the Exception thrown. You can use this object in your handler code. Throwable defines several useful methods:» getmessage() returns an appropriate message as a String» printstacktrace() dumps the series of method calls on the call stack Throwing Exceptions In classes you design, there will be occasions when it is appropriate for you to throw Exceptions. You can throw Exceptions defined in the Core API, or you can create your own. if (bad_news) { throw new FrammisException("Unexpected frammis index: "+i); else { // continue with business of your method 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 23 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 24

Defining New Exceptions Exceptions are classes just like all other classes. The same rules apply for defining them, and the same OO principles that apply to other classes you design apply to Exceptions as well. By convention, class Throwable and its subclasses have two constructors» one that takes no arguments» one that takes a String argument that can be used to produce an error message. Defining new Exception classes public class FrammisException extends Exception { public FrammisException() { super(); public FrammisException(String s) { super(s); 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 25 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 26 Naming the new Exception Try to give Exceptions names that make sense. Think of situations in which the following Exceptions might be thrown:» FileNotFoundException» MalformedURLException» StringIndexOutOfBoundsException» NegativeArraySizeException 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 27