Exceptions. CSC207 Winter 2017

Similar documents
CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSC207 Winter Section L5101 Paul Gries

ECE 122. Engineering Problem Solving with Java

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

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

Exceptions - Example. Exceptions - Example

Programming II (CS300)

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

Exceptions and Libraries

Data Structures. 02 Exception Handling

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

Programming II (CS300)

Errors and Exceptions

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

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

ITI Introduction to Computing II

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

EXCEPTION HANDLING. Summer 2018

More on Exception Handling

6.Introducing Classes 9. Exceptions

More on Exception Handling

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

Chapter 13 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

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

BBM 102 Introduction to Programming II Spring Exceptions

CS112 Lecture: Exceptions and Assertions

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

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

CSCI 261 Computer Science II

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

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

BBM 102 Introduction to Programming II Spring 2017

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

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

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

Internal Classes and Exceptions

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

Exceptions Handling Errors using Exceptions

COS226 - Spring 2018 Class Meeting # 21 April 23, 2018

Programming Languages and Techniques (CIS120)

Defensive Programming. Ric Glassey

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

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

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

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

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

Exception-Handling Overview

Java Loose Ends. 11 December 2017 OSU CSE 1

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

CS 3 Introduction to Software Engineering. 3: Exceptions

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

Sri Vidya College of Engineering & Technology Question Bank

CS159. Nathan Sprague

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

Exceptions and Design

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Exception Handling Generics. Amit Gupta

Comp 249 Programming Methodology Chapter 9 Exception Handling

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Exceptions in Java

16-Dec-10. Consider the following method:

ASSERTIONS AND LOGGING

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

Assertions and Exceptions Lecture 11 Fall 2005

CSE 143 Java. Exceptions 1/25/

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

CS 11 java track: lecture 3

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

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

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

CS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down

Software Construction

Correctness and Robustness

Exceptions and Error Handling

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

CSC 1214: Object-Oriented Programming

Chapter 12 Exception Handling

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

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

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

Introduction to Computer Science II CS S-22 Exceptions

EXCEPTIONS. Java Programming

14. Exception Handling

Administrivia. CPSC Winter 2008 Term 1. Department of Computer Science Undergraduate Events

COMP1008 Exceptions. Runtime Error

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

Introduction to Software Design

Recreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));


Java Errors and Exceptions. Because Murphy s Law never fails

2IP15 Programming Methods

Programming Language Concepts: Lecture 7

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

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

Introductory Programming Exceptions and I/O: sections

Abstract Classes, Exceptions

Transcription:

Exceptions CSC207 Winter 2017

What are exceptions? In Java, an exception is an object. Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-to-the-next-step, plod-onwards approach. Exceptions have a different model of program execution. When an exception might occur while your method is running, you have two choices: 1. Write a catch block for each kind of exception that might happen, and code to deal with the exceptional situation. 2. Let your method crash (!) and force the method that called yours to deal with it.

The Java exception type hierarchy Throwable Error AssertionError... OutOfMemoryError Exception IOException... RuntimeException ArithmeticException... ClassCastException

Exceptions in Java To throw an exception: throw Throwable; To catch an exception and deal with it: try { statements // The catch belongs to the try (like else and if) catch (ExceptionType1 parameter) { statements catch (ExceptionType2 parameter) { statements finally { // This is optional

Throwable Constructors: Throwable(), Throwable(String message) Other useful methods you can use once you catch an exception: getmessage() printstacktrace() getstacktrace()

What should you throw? You can throw an instance of Throwable or any subclass of it (whether an already defined subclass, or a subclass you define). Don t throw an instance of Error or any subclass of it: these are for unrecoverable circumstances (for example, OutOfMemoryError). Don t throw an instance of Exception: throw something more specific. It s okay to throw instances of: specific subclasses of Exception that are already defined (for example, UnsupportedOperationException) specific subclasses of Exception that you define.

Things you do not need to handle Error: Indicates serious problems that a reasonable application should not try to catch. Do not have to handle these errors because they are abnormal conditions that should never occur. RuntimeException: These are called unchecked because you do not have to handle them.

Defining your own exception You will sometimes want to define your own exception class. You get to choose a meaningful name so that it fits in the problem domain. You get to decide where in the exception hierarchy it belongs. You get to decide how it fits into your regular code.

Reminder: the Java exception hierarchy Throwable Error AssertionError... OutOfMemoryError Exception IOException... RuntimeException ArithmeticException... ClassCastException

Checked vs. Unchecked Exceptions When defining an Exception subclass, you need to decide whether to extend RunTimeException (unchecked) or Exception (checked). public class MyException extends Exception {... class MyClass { public void m() throws MyException {... if (something bad happens) { throw new MyException( oops! ); public class MyException extends RuntimeException { class MyClass { public void m() /* No throws", but it compiles! */ { if (something bad happens) { throw new MyException( oops! );

RuntimeException vs. non- RuntimeException? Java API: The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. RunTimeException (unchecked): RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. Examples: ArithmeticException, IndexOutOfBoundsException, NoSuchElementException, NullPointerException non-runtimeexception (checked): Examples: IOException, NoSuchMethodException

Guideline for which to use "Use checked exceptions for conditions from which the caller can reasonably be expected to recover." "Avoid unnecessary use of checked exceptions." If the user didn t use the API properly or if there is nothing to be done, then make it a RunTimeException. "Use run-time exceptions to indicate programming errors. The great majority of run-time exceptions indicate precondition violations." Example: Suppose method getitem(int i) returns an item at a particular index in a collection and requires that i be in some valid range. The programmer can check that before they call o.getitem(x). So sending an invalid index should not cause a checked exception to be thrown.

Another guideline for which to use Your exception will often be thrown by code you write. Programmers calling your methods need to be aware of this. If an exceptional situation is predictable by a programmer using your code (they can write an if statement to check, or otherwise ensure they re avoiding the exceptional situation), make the exception a RuntimeException subclass. If an exceptional situation is not predictable by a programmer using your code, make the exception a plain Exception subclass.

We can have cascading catches Much like an if with a series of else if clauses, a try can have a series of catch clauses. After the last catch clause, you can have a finally clause: finally {... But finally is not like a last else on an if statement: The finally clause is always executed, whether an exception was thrown or not, and whether or not the thrown exception was caught. Example of a good use for this: close open files as a clean-up step.

An example of multiple catches Suppose ExSup is the parent of ExSubA and ExSubB. try {... catch (ExSubA e) { // We do this if an ExSubA is thrown. catch (ExSup e) { // We do this if any ExSup that's not an ExSubA is thrown. catch (ExSubB e) { // We never do this, even if an ExSubB is thrown. finally { // We always do this, even if no exception is thrown.

finally vs. code after try/catch try { // do something catch(myexception e) { // handle exception finally { cleanup(); try { // do something catch(myexception e) { // handle exception cleanup(); Even if there are return statements or exceptions thrown in the try or catch blocks, the code in finally will be executed. That isn t the case with the code on the right-hand side.

Documenting Exceptions /** * Return the mness of this object up to mlimit. * @param mlimit The max mity to be checked. * @return int The mness up to mlimit. * @throws MyException If the local alphabet has no m. */ public void m(int mlimit) throws MyException {... if (...) throw new MyException ("oops!") {... You need both: the Javadoc comment is for human readers, and the throws is for the compiler and for humans. Both the reader and the compiler are checking that caller and callee have consistent interfaces.