Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.

Slides:



Advertisements
Similar presentations
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Advertisements

Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 13 In a language without exception handling: When an exception occurs, control goes to the operating.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Object Oriented Programming
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Slides Credit Umair Javed LUMS Web Application Development.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
COMP Exception Handling Yi Hong June 10, 2015.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
C OMP 401 E XCEPTIONS -R EMAINDER Instructor: Prasun Dewan.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Introduction to OO Program Design
Handling Exceptions.
Web Design & Development Lecture 7
Java Exceptions Dan Fleck CS211.
Exception Handling Contents
Java Basics Exception Handling.
Exception Handling and Event Handling
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed –User interface and computation code mixed

Argument Printer package main; public class AnArgPrinter{ public static void main(String args[]) { System.out.println(args[0]); } Exception will be reported to the user

Error check if (args.length == 0 ) { System.out.println("Did not specify the argument to be printed. Terminating program."); System.exit(-1); } else { System.out.println(args[0]); } Regular and error code mixed together

Exception handler try { System.out.println(args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Did not specify the argument to be printed. Terminating program."); System.exit(-1); } Regular and error code separate

Printing multiple arguments: main public static void main (String args[]) { echoLines(numberOfInputLines(args)); }

numberOfInputLines static int numberOfInputLines(String[] args) { try { return Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Did not enter an argument.") return 0; } Computation and UI mixed Arbitrary legal value returned, program not halted

echoLines static void echoLines (int numberOfInputLines) { try { for (int inputNum = 0; inputNum < numberOfInputLines; inputNum++) System.out.println(inputStream.readLine()); } catch (IOException e) { System.out.println("Did not input " + numberOfInputLines + " input strings before input was closed. "); System.exit(-1); } Decision to halt without full context

Moral: Separate error detection and handling In this example –Let echo lines and numberOfInputLines not do the error handling. –All they do is error reporting –Main does error handling and associated UI

Error code solution Pass back error codes to main –Works for procedures as we can make it return value instead of void –Does not work for functions as error code may be legal return value Integer function returning all possible integer values

Global variable solution Store error codes in common variables –Does not work when there are multiple calls to the same method A call may overwrite value written by another call –Variable may accessed by other methods sharing its scope

Exception propagation Java lets exceptions be “returned instead of regular values. These propagate through call chain until some method handles them

Propagating echoLines static void echoLines (int numberOfInputLines) throws IOException { for (int inputNum = 0; inputNum < numberOfInputLines; inputNum++) System.out.println(inputStream.readLine( )); } Tells caller that passing it the exception

Propagating numberOfInputLines static int numberOfInputLines(String[] args) throws ArrayIndexOutOfBoundsException { return Integer.parseInt(args[0]); }

Handling in main public static void main (String args[]) { try { echoLines(numberOfInputLines(args)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Did not enter an argument. Assuming a single input line.”); echoLines(1); } catch (IOException e) { System.out.println("Did not input the correct number of input strings before input was closed. "); } Has context IO exception not caught

Handling in main public static void main (String args[]) { try { echoLines(numberOfInputLines(args)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Did not enter an argument. Assuming a single input line.”); try { echoLines(1); } catch (IOException ioe) { System.out.println("Did not input the one input string, which is the default in case of missing argument, before input was closed. "); } } catch (IOException e) { System.out.println("Did not input the correct number of input strings before input was closed. "); } Must be different names

Passing the buck in main public static void main (String args[]) throws IOException, ArrayIndexOutOfBoundsException { echoLines(numberOfInputLines(args)); } Bad idea as interpreter’s messages may be meaningless to the user

Omitting IOException in throws clause static void echoLines (int numberOfInputLines) { for (int inputNum = 0; inputNum < numberOfInputLines; inputNum++) System.out.println(inputStream.readLine( )); } Java complains IOException neither handled nor declared Caller does not know what it must handle

Omitting ArrayIndexOutOfBoundsException in throws clause static int numberOfInputLines(String[] args) { return Integer.parseInt(args[0]); } No complaints from Java

Java has two kinds of exceptions Unchecked exceptions –Called “runtime”, but all exceptions are runtime! –Subclasses of RunTimeException E.g. ArrayIndexOutofBoundsException –Uncaught exceptions need not be declared Checked exceptions –Uncaught exceptions must be declared Rationale for division?

Misleading header static void safeArrayIndexer throws ArrayIndexOutOfBoundsException () { String args[] = {“hello”, “goodbye”}; System.out.println(args[1]); } Array index does not imply exception Java cannot tell the difference Array index out of bounds guaranteed to not happen

Reasons for exceptions User error –Programmer cannot prevent it –Should be acked Internal error –Programmer can prevent –A method that can be erroneous probably is not really erroneous –Acking is probably misleading

Justification of Java Rules Java rules justified if: Checked (Non-runtime) exceptions = user errors Unchecked (runtime) exceptions = internal errors

Problems with Java rules Unchecked exceptions can be caused by user error static int numberOfInputLines(String[] args) { return Integer.parseInt(args[0]); }

Approach 1: Voluntarily list exception static int numberOfInputLines(String[] args) throws ArrayIndexOutOfBoundsException { return Integer.parseInt(args[0]); } No way to force every caller that does not handle it to ack it.

Approach 2: Convert to checked exception static int numberOfInputLines(String[] args) throws IOException { try { return Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { throw new IOException (“First argument missing”); } Exception object thrown explicitly message

Checked vs. Unchecked Unchecked –No rules Checked –uncaught in method body => acknowledged in method header –unacknowledged in method header => caught in method body –unacknowledged in interface method-header => unacknowledged in class method-header –Interface can be used to force method implementations to catch exceptions

Interface/Class relationship public interface StringEnumeration {... public String nextElement(); } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() { try { return inputStream.readLine(); } catch (IOException e) { return “”; }

Interface/Class relationship public interface StringEnumeration {... public String nextElement(); } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() throws IOException{ return inputStream.readLine(); }

Interface/Class relationship public interface StringEnumeration {... public String nextElement(); } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() throws java.util.NoSuchElementException { if (!hasMoreElements()) throw new java.util.NoSuchElementException(); return inputStream.readLine(); } Unchecked, as most users will call hasMoreElements before nextElement()

Standard Enumeration interface package java.util; public interface Enumeration {... public Object nextElement(); } public class AnInputStreamScanner implements java.util.Enumeration{... public Object nextElement() throws java.util.NoSuchElementException { if (!hasMoreElements()) throw new java.util.NoSuchElementException(); return inputStream.readLine(); } Good idea to throw this exception when no more elements

Throwing multiple exceptions public interface StringEnumeration {... public String nextElement() throws java.io.IOException; } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() throws java.util.NoSuchElementException, java.io.IOException { if (!hasMoreElements()) throw new java.util.NoSuchElementException(); return inputStream.readLine(); } When no more elements When next element erroneous because of user error (e.g. scanning rules violated)

Printing debugging information catch (ArrayIndexOutOfBoundsException e) { System.out.println(e); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } e.getMessage() Stack when exception is thrown

Printing stack Stack that existed when exception was thrown

Exceptions in initialization int numberOfInputLines = numberOfInputLines() –Checked exception not being handled or acknowledged Do initialization in method –public static void main (String args) { try { numberOfInputLines = numberOfInputLines() } catch (IOException e) { } }

Approach 2: Convert to existing checked exception static int numberOfInputLines(String[] args) throws IOException { try { return Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { throw new IOException(“First argument missing”); } Exception object thrown explicitly

Approach 3: Convert to new checked exception static int numberOfInputLines(String[] args) throws IOException { try { return Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { throw new AMissingArgumentException(“First argument missing”); } Our own exception

Creating Exception Class public class AMissingArgumentException extends java.io.IOException { public AMissingArgumentException(String message) { super(message); } No interface! Not adding any methods

Checked vs. Unchecked Programmer-defined Exceptions An exception class must be subclass of existing exception classes Subclass of RunTimeException is unchecked All other exceptions are checked Java does not define exception interfaces Neither can we as a result

Handling programmer-defined exceptions try { echoLines(numberOfInputLines(args)); } catch (AMissingArgumentException e) { System.out.println(e); System.exit(-1); } catch (IOException e) { System.out.println(e); System.exit(-1); }

Removing Code Duplication try { echoLines(numberOfInputLines(args)); } catch (IOException e) { System.out.println(e); System.exit(-1); } AMissingArgumentException is subclass

Removing Code Duplication try { echoLines(numberOfInputLines(args)); } catch (IOException e) { System.out.println(e); System.exit(-1); } catch (AMissingArgumentException e) { System.out.println(e); } AMissingArgumentException processed here List exception subclass before superclass Unreachable block

Interface/Class relationship public interface StringEnumeration { public boolean hasMoreElements(); public String nextElement() throws Exception; } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() throws IOException{ return inputStream.readLine(); } Stronger advertisement allowed void print (StringEnumeration stringEnumeration) { try { while (stringEnumeration.hasMoreElements()) System.out.println(stringEnumeration.nextElement()); } catch (Exception e) {…} } Can handle IOException

Interface/Class relationship public interface StringEnumeration {... public String nextElement() throws IOException; } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() { try { return inputStream.readLine(); } catch (IOException e) { return “”; } Stronger advertisement allowed void print (StringEnumeration stringEnumeration) { try { while (stringEnumeration.hasMoreElements()) System.out.println(stringEnumeration.nextElement()); } catch (IOException e) {…} }

Interface/Class relationship public interface StringEnumeration { public boolean hasMoreElements(); public String nextElement() throws IOException; } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() throws Exception { return inputStream.readLine() + … ; } Weaker advertisement not allowed void print (StringEnumeration stringEnumeration) { try { while (stringEnumeration.hasMoreElements()) System.out.println(stringEnumeration.nextElement()); } catch (IOException e) {…} } Cannot handle Exception

Interface/Class relationship public interface StringEnumeration { public boolean hasMoreElements(); public String nextElement(); } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() throws IOException{ return inputStream.readLine(); } Weaker advertisement not allowed void print (StringEnumeration stringEnumeration) { while (stringEnumeration.hasMoreElements()) System.out.println(stringEnumeration.nextElement()); } Not handling IOException

Implementation/body relationship public interface StringEnumeration { public boolean hasMoreElements(); public String nextElement() throws Exception; } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() throws Exception { return inputStream.readLine(); } void print (StringEnumeration stringEnumeration) { try { while (stringEnumeration.hasMoreElements()) System.out.println(stringEnumeration.nextElement()); } catch (Exception e) {…} } Can handle IOException Stronger advertisement allowed

Implementation/body relationship public interface StringEnumeration { public boolean hasMoreElements(); public String nextElement() throws AMissingArgumentException; } public class AnInputStreamScanner implements StringEnumeration {... public String nextElement() throws AMissingArgumentException { return inputStream.readLine(); } void print (StringEnumeration stringEnumeration) { try { while (stringEnumeration.hasMoreElements()) System.out.println(stringEnumeration.nextElement()); } catch (AMissingArgumentException e) {…} } Cannot handle IOException Weaker advertisement not allowed

IS-A Rule for Exceptions Exception of type T1 uncaught in method body => exception of type T2, where T1 IS-A T2, acknowledged in method header Exception of type T1 acknowledged in interface method-header => exception of type T2, where T2 IS-A T1, acknowledged in class method-header If you are bad, you should not say you are good. –People will be disappointed If you are good, you can say you are bad –Don’t let people down

Catching expected events try { for (;;) { String s = inputStream.readLine(); process(s); } } catch (IOException e) { }; Using EOF to terminate the loop Bad style, exception handler processes expected event more efficient: no extra if check

Intra-method propagation while (enumeration.hasMoreElements()) try { System.out.println((String) enumeration.nextElement()); } catch (ClassCastException e) { e.printStackTrace());} try { while (enumeration.hasMoreElements()) System.out.println((String) enumeration.nextElement()); } catch (ClassCastException e) {e.printStackTrace());} println terminated and exception propagated to enclosing loop, which is also terminated, and catch executed Println terminated, catch executed, and loop continues

Terminating loop vs. statement Independent errors can be collected –5 % 2 ^ 1 Dependent errors cannot be: – / - 2