Java Exceptions Version June 2009

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

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

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

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

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

Exceptions Handling Errors using Exceptions

I/O. Output. Input. Input ของจาวา จะเป น stream จะอ าน stream ใช คลาส Scanner. standard input. standard output. standard err. command line file.

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

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

BBM 102 Introduction to Programming II Spring Exceptions

COMP1008 Exceptions. Runtime Error

Programming Languages and Techniques (CIS120)

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

For more details on SUN Certifications, visit

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

COMP-202 Unit 9: Exceptions

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

Internal Classes and Exceptions

CS193j, Stanford Handout #25. Exceptions

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

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:

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

CMSC 202. Exceptions


BBM 102 Introduction to Programming II Spring 2017

Exception-Handling Overview

Java Programming Unit 7. Error Handling. Excep8ons.

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

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

Programming Languages and Techniques (CIS120e)

Chapter 13 Exception Handling

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

Exceptions - Example. Exceptions - Example

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

CSE 331 Software Design & Implementation

Object Oriented Programming Exception Handling

Exceptions in Java

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

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

CS 3 Introduction to Software Engineering. 3: Exceptions

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

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

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

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

CS159. Nathan Sprague

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

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

Program Correctness and Efficiency. Chapter 2

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

C16b: Exception Handling

Programming II (CS300)

Chapter 12 Exception Handling

G Programming Languages - Fall 2012

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

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

Comp 249 Programming Methodology Chapter 9 Exception Handling

Object Oriented Programming

COMP-202 Unit 9: Exceptions

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Data Structures. 02 Exception Handling

6.Introducing Classes 9. Exceptions

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

ECE 122. Engineering Problem Solving with Java

Introduction to Software Design

Std 12 Lesson-10 Exception Handling in Java ( 1

Programming Languages and Techniques (CIS120)

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

Introductory Programming Exceptions and I/O: sections

Exception Handling Generics. Amit Gupta

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

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

Java Errors and Exceptions. Because Murphy s Law never fails

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

Events and Exceptions

CSC 1214: Object-Oriented Programming

CSPP : Introduction to Object-Oriented Programming

Fundamentals of Object Oriented Programming

Chapter 14. Exception Handling and Event Handling ISBN

Module 4 - 异常和断言 一 选择题 :

Preconditions. CMSC 330: Organization of Programming Languages. Signaling Errors. Dealing with Errors

Object-Oriented Principles and Practice / C++

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

Exceptions and assertions

Programming II (CS300)

Introduction to Java. Handout-3a. cs402 - Spring

14. Exception Handling

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

Errors and Exceptions

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

17. Handling Runtime Problems

Exception handling & logging Best Practices. Angelin

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Loose Ends. 11 December 2017 OSU CSE 1

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

16-Dec-10. Consider the following method:

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

G52CPP C++ Programming Lecture 16

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Transcription:

Java Exceptions Version June 2009

Motivation Report errors, by delegating error handling to higher levels Callee might not know how to recover from an error Caller of a method can handle error in a more appropriate way than the callee Localize error handling code, by separating it from functional code Functional code is more readable Error code is centralized, rather than being scattered 2

The world without exceptions (I) If a non locally remediable error happens while method is executing, call System.exit() A method causing an unconditional program interruption in not very dependable (nor usable) 3

The world without exceptions (II) If errors happen while method is executing, we return a special value Special values are different from normal return value (e.g., null, -1, etc.) Developer must remember value/meaning of special values for each call to check for errors What if all values are normal? double pow(base, exponent) pow(-1, 0.5); //not a real 4

Real problems Code is messier to write and harder to read if( somefunc() == ERROR ) // detect error //handle the error else //proceed normally Only the direct caller can intercept errors (no delegation to any upward method) 5

Example Read file open the file determine file size allocate that much memory read the file into memory close the file open () readfile() (caller) (callee) size() (callee) alloc() (callee) read() (callee) close() (callee) All of them can fail 6

Correct (but boring) int readfile { open the file; if (operationfailed) return -1; determine file size; if (operationfailed) return -2; allocate that much memory; if (operationfailed) { close the file; return -3; read the file into memory; if (operationfailed) { close the file; return -4; close the file; if (operationfailed) return -5; return 0; Lots of error-detection and error-handling code To detect errors we must check specs of library calls (no homogeneity) Unreadable 7

Wrong (but quick and readable) int readfile { open the file; determine file size; allocate that much memory; read the file into memory; close the file; return 0; Which one would YOU use? 8

Using exceptions (nice) try { open the file; determine file size; allocate that much memory; read the file into memory; close the file; catch (fileopenfailed) { dosomething; catch (sizedeterminationfailed) { dosomething; catch (memoryallocationfailed) { dosomething; catch (readfailed) { dosomething; catch (fileclosefailed) { dosomething; 9

Basic concepts 1. The code causing the error will generate an exception Developers code Third-party library 1. At some point up in the hierarchy of method invocations, a caller will intercept and stop the exception 2. In between, methods can Ignore the exception (complete delegation) Intercept without stopping (partial delegation) 10

Syntax Java provides three keywords Try Contains code that may generate exceptions Catch Defines the error handler Throw Generates an exception We also need a new entity Exception class 11

Generation 1. Declare an exception class 2. Mark the method generating the exception 3. Create an exception object 4. Throw upward the exception 12

Generation // java.lang.exception public class EmptyStack extends Exception { (1) class Stack{ public Object pop() throws EmptyStack { (2) if(size == 0) { Exception e = new EmptyStack(); throw e; (4)... (3) 13

throws Method interface must declare exception type(s) generated within its implementation (list with commas) Either generated and thrown by method, directly Or generated by other methods called within the method and not caught 14

throw Execution of current method is interrupted immediatelly Catching phase starts 15

Interception Catching exceptions generated in a code portion try { // in this piece of code some // exceptions may be generated stack.pop();... catch (StackEmpty e) { // error handling System.out.println(e);... 16

Execution flow open and close can generate a FileError Suppose read does not generate exceptions System.out.print("Begin"); File f = new File( foo.txt ); try{ f.open(); f.read(); f.close(); catch(fileerror fe){ System.out.print("Error"); System.out.print("End"); 17

Execution flow No exception generated System.out.print("Begin"); File f = new File( foo.txt ); try{ f.open(); f.read(); f.close(); catch(fileerror fe){ System.out.print("Error"); System.out.print("End"); 18

Execution flow open() generates an exception read() and close() are skipped System.out.print("Begin"); File f = new File( foo.txt ); try{ f.open(); f.read(); f.close(); catch(fileerror fe){ System.out.print("Error"); System.out.print("End"); 19

Multiple catch Capturing different types of exception is possible with different catch blocks try {... catch(stackempty se) { // here stack errors are handled catch(ioexception ioe) { // here all other IO problems are handled 20

Execution flow open and close can generate a FileError read can generate a IOError System.out.print("Begin"); File f = new File( foo.txt ); try{ f.open(); f.read(); f.close(); catch(fileerror fe){ System.out.print( File err ); catch(ioerror ioe){ System.out.print( I/O err ); System.out.print("End"); 21

Execution flow close fails File error is printed System.out.print("Begin"); File f = new File( foo.txt ); try{ f.open(); f.read(); f.close(); catch(fileerror fe){ System.out.print( File err ); catch(ioerror ioe){ System.out.print( I/O err ); System.out.print("End"); 22

Execution flow read fails I/O error is printed System.out.print("Begin"); File f = new File( foo.txt ); try{ f.open(); f.read(); f.close(); catch(fileerror fe){ System.out.print( File err ); catch(ioerror ioe){ System.out.print( I/O err ); System.out.print("End"); 23

Matching rules Only one handler is executed The more specific handler is selected, according to the exception type Handlers must be ordered according to their generality 24

Matching rules Exception + general Error FatalEx IOErr FileErr - general 25

Matching rules class Error extends Exception{ class IOErr extends Error{ class FileErr extends Error{ class FatalEx extends Exception{ try{ /* */ catch(ioerr ioe){ /* */ catch(error er){ /* */ catch(exception ex){ /* */ - general + general 26

Matching rules class Error extends Exception{ class IOErr extends Error{ class FileErr extends Error{ class FatalEx extends Exception{ try{ /* */ catch(ioerr ioe){ /* */ catch(error er){ /* */ catch(exception ex){ /* */ IOErr is generated 27

Matching rules class Error extends Exception{ class IOErr extends Error{ class FileErr extends Error{ class FatalEx extends Exception{ try{ /* */ catch(ioerr ioe){ /* */ catch(error er){ /* */ catch(exception ex){ /* */ Error or FileErr is generated 28

Matching rules class Error extends Exception{ class IOErr extends Error{ class FileErr extends Error{ class FatalEx extends Exception{ try{ /* */ catch(ioerr ioe){ /* */ catch(error er){ /* */ catch(exception ex){ /* */ FatalEx is generated 29

Nesting Try/catch blocks can be nested E.g. error handler may generate new exceptions try{ /* Do something */ catch( ){ try { /* Log on file */ catch( ){ /* Ignore */ 30

Generate and catch When calling code, which possibly raises an exception, the caller can 1. Catch 2. Propagate 3. Catch and re-throw 31

[1] Catch class Dummy { public void foo(){ try{ FileReader f; f = new FileReader( file.txt ); catch (FileNotFound fnf) { // do something 32

[2] Propagate class Dummy { public void foo() throws FileNotFound{ FileReader f; f = new FileReader( file.txt ); 33

[2] Propagate (cont d) Exception not caught can be propagated till main() and VM class Dummy { public void foo() throws FileNotFound { FileReader f = new new FileReader( file.txt ); class Program { public static void main(string args[]) throws FileNotFound { Dummy d = new new Dummy(); d.foo(); 34

[3] Re-throw class Dummy { public void foo(){ try{ FileReader f; f = new FileReader( file.txt ); catch (FileNotFound fnf) { // handle fnf, e.g., print it throw fnf; 35

Exceptions hierarchy Internal Error, Hard failure in VM (e.g. out of memory) Object Throwable Programming error (e.g. null pointer, out of bounds, cast error) Error Exception unchecked checked Runtime Exception unchecked 36

Custom exceptions It is possible to define new types of exceptions If the ones provided by the system are not enough Just sub-classing Throwable or one of its descendants 37

Checked and unchecked Unchecked exceptions Their generation is not foreseen (can happen everywhere) Need not to be declared (not checked by the compiler) Generated by JVM Checked exceptions Exceptions declared and checked Generated with throw 38

finally The keyword finally allows specifying actions that must be always executed Dispose resources Close a file After all catch branches (if any) MyFile f = new new MyFile(); if if (f.open( myfile.txt")) { try try { exceptionalmethod(); finally { f.close(); 39

Exceptions and loops (I) For errors affecting a single iteration, the try-catch blocks is nested in the loop. In case of exception the execution goes to the catch block and then proceed with the next iteration. while(true){ try{ // potential exceptions catch(anexception e){ // handle the anomaly

Exceptions and loops (II) For serious errors compromising the whole loop the loop is nested within the try block. In case of exception the execution goes to the catch block, thus exiting the loop. try{ while(true){ // potential exceptions catch(anexception e){ // print error message