CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Similar documents
Exceptions. CSC207 Winter 2017

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. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Errors and Exceptions

Programming II (CS300)

Exceptions and Libraries

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

Exceptions - Example. Exceptions - Example

Data Structures. 02 Exception Handling

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

Programming II (CS300)

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

BBM 102 Introduction to Programming II Spring Exceptions

6.Introducing Classes 9. Exceptions

Chapter 13 Exception Handling

EXCEPTION HANDLING. Summer 2018

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

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

BBM 102 Introduction to Programming II Spring 2017

More on 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.

More on Exception Handling

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

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

Programming Languages and Techniques (CIS120)

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

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

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

Internal Classes and Exceptions

ITI Introduction to Computing II

CS 3 Introduction to Software Engineering. 3: Exceptions

ITI Introduction to Computing II

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

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

Exceptions Handling Errors using Exceptions

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

Sri Vidya College of Engineering & Technology Question Bank

Defensive Programming. Ric Glassey

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

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

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

CSCI 261 Computer Science II

Chapter 12 Exception Handling

Exception-Handling Overview

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

CS112 Lecture: Exceptions and Assertions

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

14. Exception Handling

Exceptions in Java

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

CSC 1214: Object-Oriented Programming

Correctness and Robustness

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

COMP1008 Exceptions. Runtime Error

Assertions and Exceptions Lecture 11 Fall 2005

16-Dec-10. Consider the following method:

Introduction to Computer Science II CS S-22 Exceptions

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

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

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

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

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

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

Abstract Classes, Exceptions

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

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

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

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

Java Loose Ends. 11 December 2017 OSU CSE 1

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

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

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

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

EXCEPTIONS. Java Programming

Comp 249 Programming Methodology Chapter 9 Exception Handling

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

Exception Handling in Java

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

Introductory Programming Exceptions and I/O: sections

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

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

CS159. Nathan Sprague

Exceptions and Error Handling

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

Exception Handling Generics. Amit Gupta

Exceptions and Design

CS 209 Programming in Java #10 Exception Handling

For more details on SUN Certifications, visit

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Software Construction

ASSERTIONS AND LOGGING

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

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

Object Oriented Programming

Transcription:

Exceptions CSC207 Winter 2018 1

What are exceptions? Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-tothe-next-step, plod-onwards approach. Often the result of some input (e.g. from user or file) Exception Handling creates programs that can resolve or handle exceptions These programs recover gracefully from errors we call these programs robust or fault-tolerant 2

Exceptions in Java In Java, an exception is an object. 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. (try/catch) 2. Let your method crash (!) and force the method that called yours to deal with it. (throws) 3

The Java Exception Type Hierarchy Throwable Error Exception AssertionError... OutOfMemoryError IOException... RuntimeException ArithmeticException... ClassCastException 4

Things the compiler does not force you 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 the client is not expected to have to handle them. Examples: arithmetic exceptions: dividing by zero pointer exceptions: null pointers indexing exceptions: index out of bounds in array 5

throw & try/catch & throws 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 To say you aren t going to deal with exceptions (or may throw your own): accessmod returntype methodname (parameters) throws Throwable {... 6

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

throw: 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. 8

try/catch: Some things not to catch Don t catch Error: You can t be expected to handle these. Don t catch Throwable or Exception: Catch something more specific. (You can certainly do so when you re experimenting with exceptions. Just don t do it in real code without a good reason.) 9

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. 10

Checked vs. Unchecked Exceptions When defining an Exception subclass, you need to decide whether to extend RunTimeException (unchecked at compile time) or Exception (checked at compile time). 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! ); 11

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 12

Reminder: the Java Exception Hierarchy Throwable Unchecked Error Checked Exception AssertionError... OutOfMemoryError IOException... Unchecked RuntimeException ArithmeticException... ClassCastException 13

Checked vs. unchecked: Guideline for which to use If a client [caller] can reasonably be expected to recover from an exception, make it a checked exception. If a client [caller] cannot do anything to recover from the exception, make it an unchecked exception. Avoid unnecessary use of checked exceptions - they make the API unpleasant to use https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html 14

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. 15

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. 16

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. 17

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. 18