Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

Similar documents
Java Loose Ends. 11 December 2017 OSU CSE 1

Object Oriented Programming. Week 7 Part 1 Exceptions

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

CSE 331 Software Design & Implementation

ECE 122. Engineering Problem Solving with Java

Program Correctness and Efficiency. Chapter 2

Object Oriented Programming Exception Handling

6.Introducing Classes 9. Exceptions

Chapter 13 Exception Handling

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

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

Object Oriented Programming

Internal Classes and Exceptions

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

Errors and Exceptions

CS193j, Stanford Handout #25. Exceptions

Programming II (CS300)

BBM 102 Introduction to Programming II Spring Exceptions

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Lecture 9: Parameter Passing, Generics and Polymorphism, Exceptions

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

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

BBM 102 Introduction to Programming II Spring 2017

CS159. Nathan Sprague

EXCEPTION HANDLING. Summer 2018

Assertions and Exceptions Lecture 11 Fall 2005

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Programming Languages and Techniques (CIS120)

Exception Handling in C++

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

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

Exception Handling. Chapter 9

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

Comp 249 Programming Methodology Chapter 9 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.

Sri Vidya College of Engineering & Technology Question Bank

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

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

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

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

Exceptions Handling Errors using Exceptions

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

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

Programming II (CS300)

CS 3 Introduction to Software Engineering. 3: Exceptions

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

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

Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java. Xiaoqing Lv 1 1 huihua College Of Hebei Normal University,

Exception-Handling Overview

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

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

Exceptions and assertions

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

Std 12 Lesson-10 Exception Handling in Java ( 1

Lecture 10 Assertions & Exceptions

CSE 331 Software Design and Implementation. Lecture 12 Assertions & Exceptions

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Fundamentals of Object Oriented Programming

Exceptions in Java

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

Data Structures. Subodh Kumar. Dept of Computer Sc. & Engg. IIT Delhi

Exception Handling Generics. Amit Gupta

Object Oriented Programming

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

Programming in Java

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

Advanced Flow of Control -- Introduction

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

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

14. Exception Handling

16-Dec-10. Consider the following method:

Checked and Unchecked Exceptions in Java

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Lecture 12 Assertions & Exceptions

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

Input-Output and Exception Handling

Java Exceptions Version June 2009

Correctness and Robustness

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

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Object-Oriented Principles and Practice / C++

Designing Robust Classes

Error Management in Compilers and Run-time Systems

Software Design and Analysis for Engineers

Data Structures. 02 Exception Handling

CSCI 261 Computer Science II

CPSC 427: Object-Oriented Programming

Lecture 19 Programming Exceptions CSE11 Fall 2013

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

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

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

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

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

Main concepts to be covered. Handling errors. Some causes of error situations. Not always programmer error. Defensive programming.

Chapter 14. Exception Handling and Event Handling

WA1278 Introduction to Java Using Eclipse

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

Transcription:

s Computer Science and Engineering College of Engineering The Ohio State University Lecture 15

Throwable Hierarchy extends implements Throwable Serializable Internal problems or resource exhaustion within VM Thrown by Java SDK methods or VM itself unrecoverable Beyond the program s ability to control or handle Little you can do: abort the program s Problems within the application Thrown by Java SDK or programmer application recoverable (maybe) Corrective actions within program may be possible

Hierarchy extends implements Throwable Serializable VirtualMachine Assertion OutOfMemory

Hierarchy extends implements Throwable Serializable Runtime IO s derived from Runtime Examples: bad cast, out-of-bounds array access, dereferencing a null pointer Happen because an error exists in your program Your fault s that do not derive from Runtime Example: trying to open a malformed URL Happen because of externalities (the outside world) Not your fault

Hierarchy extends implements Throwable Serializable Runtime IO NullPointer Arithmetic SQL IndexOutOf Bounds ArrayIndexOutOf Bounds

Throwable (sub)hierarchy extends implements Throwable Serializable VirtualMachine Assertion NullPointer Runtime Arithmetic IO SQL OutOfMemory IndexOutOf Bounds ArrayIndexOutOf Bounds

Good Practice: When to Use Reserve for unexpected or unusual behavior Good: to signal file does not exist Bad: to signal end of file Terrible: to signal end-of-line (ie for control flow) Particularly appropriate when client can not guarantee the requires clause of a method Example: existence of a file. First checking for the file does not help because file could be deleted after check but before method is called Concurrency of world with which program interacts means that some requires clauses can not be unilaterally guaranteed by client, as required by design-by-contract More on this in a future lecture

Syntax of Try/Catch Blocks Vocabulary: s (and s) are thrown by a component implementation caught by a client In client, a try/catch block is used to catch try { statements } catch(exceptiontype1 identifier1) { handler for type1 } catch(exceptiontype2 identifier1) { handler for type2 }... If nothing is thrown during execution of the statements in the try clause: Try clause finishes successfully All catch clauses are ignored

Example String filename =... try { //Create the file File f = new File(filename); if (f.createnewfile()) {... //file creation succeeded } else {... //file already exists }... //either way, can use f here } catch (IO e) { //deal with IO problem (eg disk full) } catch (Security e) { //some permission problem }

Catching a Throwable If something is thrown during excecution of the statements in the try clause: 1. The rest of the code in the try block is skipped 2. The catch clauses are examined top to bottom for the first matching catch (based on type compatibility) catch (Some e) matches subtypes of Some 3. If an appropriate catch clause is found: Body of catch clause is executed Remaining catch clauses are skipped 4. If no such a catch clause is found: The exception is thrown to outer block, which is either A try block (that potentially handles it, in same manner) A method body (resulting in it being thrown to its client) Consequence: A catch clause for a subclass of Some cannot follow a catch clause for Some for the same try

Good Practice: Specific Catching Can be tempting to bundle all exception catching into one clause try {... } catch ( e) {... } Usually, however, properly handling an exception is more type-specific Therefore, catch each (relevant) exception type separately Similar concern as coding to the interface An exception s declared type should be specific enough to provide information needed by the client for recovery, but not more

Handling a Throwable Implementations are layered Objects are both clients and components A Voter B PollingPlace C? e CitizenRoll How should B handle the throwable e from C? Three choices for body of catch clause in B Handle the exceptional situation, effectively masking the issue from A Pass e on to A But e might not make sense to A, which does not even know about C! Create and throw a new throwable, e2, for A chaining can link e2 to its cause (e)

Good Practice: Never Suppress An empty catch clause is a red flag Usually indicates laziness try {... } catch (IO e) { } There are very rare instances where no action actually does properly handle the situation If so, document code with clear justification More subtle: catch clause that logs try {... } catch (IO e) { e.printstacktrace(); } This also effectively hides the exception without actually having handled it

(Poor) Example String filename = "/nosuchdir/somefile"; try { //Create the file new File(filename).createNewFile(); } catch (IO e) { //Display the exception that occurred System.out.println( Unable to create + filename + : + e.getmessage()); } Output Unable to create /nosuchdir/somefile: The system cannot find the path specified

Finally Clause Some actions should be performed whether or not exceptions occur Example: releasing resources such as database or network connections Syntax try {... } catch (IO e) {... } finally {... //always executed } The finally clause is executed: After the try clause in the case of normal execution After the catch clause in the case of an exception

Checked vs Unchecked s Unchecked s Ubiquity: Possible sources (statements) are common Examples: any dereference could be of null, any memory allocation could exhaust memory Condition could arise in practically any method Consequently, all methods allowed to throw them Checked exceptions Operation-specific Examples: working with file system or network Conditions could arise in limited number of methods A method can only throw (checked) exceptions explicitly declared in its signature Image load() throws IO, EOF {...} A client must catch all declared checked exceptions These last two requirements are checked by compiler

Distinguishing Checked & Unchecked extends implements Throwable Serializable VirtualMachine Assertion NullPointer Runtime Arithmetic IO SQL OutOfMemory Unchecked s IndexOutOf Bounds ArrayIndexOutOf Bounds Checked s

Rule Unchecked exceptions are: Subclasses of, or Subclasses of Runtime The rest are checked exceptions

Throwing Throwables To signal an exceptional situation Component creates a new throwable object Component throws it with throws keyword Syntax String readdata(scanner in) throws EOF {... while(...) { if (!in.hasnext()) { //EndOfFile encountered if(n < len) { throw (new EOF( File too long )); }... } return s; } For checked exceptions: Dynamic type of the thrown exception must be subclass of an exception type declared in method signature

Creating new Classes Throwable hierarchy can be subclassed to create new application-specific exception types class Temperature extends {... } Inherit Throwable s String for informal description t = new Temperature( Engine overheated ); throw (new EOF( File too long )); Why create new exception types? New class can declare new fields and methods Can provide more structured information to client Eg Temperature includes value of temperature that triggered the exception Client catch clause is determined by exception type Can distinguish a problem for which distinct handling logic will (likely) be required on client s side Eg Temperatures will require modifying the engine s temperature before repeating the operation

Good Practice: New s Use standard exceptions if possible Good litmus test: are particular methods needed to aid in recovery? Prefer checked exceptions Extend, not or Runtime Naming convention Class name ends in (see SDK)

Catching Checked s Choices for body of catch clause corresponding to checked exception e Mask the problem by handling the exceptional situation Rethrow e on up to client and declare exception type in signature (throws) Create and throw a new throwable, e2, on up to client e2 could be checked, in which case it must be declared in signature e2 could be unchecked, in which case it should not be declared in signature

Chaining Body of a catch clause often creates and throws a new throwable Used to change the type of exception Map failure to a mode that makes sense to client Original exception, however, might still be useful Example: Debugging by looking at the trail of cascading exceptions Chaining: A Throwable has a cause (another throwable) catch (SQL e) { Servlet se = new Servlet(); se.setcause(e); throw se; } At client (or higher), original exception can be retrieved catch (Servlet e) { Throwable cause = e.getcause();

Summary Throwable hierarchy s, exceptions (& run-time exceptions) Checked vs unchecked throwables Mechanics Try/catch block Declaration in method signatures chaining