Lecture 9: Exceptions in Java CS201j: Engineering Software

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
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 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.
Java Software Solutions Foundations of Program Design Sixth Edition
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
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.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
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.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 9: Designing Exceptionally.
Today’s lecture Review of chapter 8 Go over examples.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
Cs205: engineering software university of virginia fall 2006 Programming Exceptionally David Evans
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Eighth Lecture Exception Handling in Java
Java Exceptions a quick review….
Exceptions In this lecture:
Exceptions: When things go wrong
Chapter 10 – Exception Handling
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Exceptions, Interfaces & Generics
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
COMPSCI 230 S Programming Techniques
Testing and Exceptions
CS Week 10 Jim Williams, PhD.
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
Exceptions 10-Nov-18.
Handling Exceptions.
Advanced Programming Behnam Hatami Fall 2017.
EE422C Software Implementation II
ATS Application Programming: Java Programming
Exceptions & exception handling
Exception Handling and Reading / Writing Files
Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Java Exception Very slightly modified from K.P. Chow
CSE 143 Java Exceptions 1/18/2019.
Java Exceptions Dan Fleck CS211.
CMSC 202 Exceptions 2nd Lecture.
Exceptions 25-Apr-19.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Exceptions 22-Apr-19.
Exceptions.
Exceptions 10-May-19.
Why do we need exceptions?
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
Exceptions.
Exception Handling.
Exceptions and Exception Handling
Presentation transcript:

Joel Winstead http://www.cs.virginia.edu/~jaw2u Lecture 9: Exceptions in Java CS201j: Engineering Software University of Virginia Computer Science Joel Winstead http://www.cs.virginia.edu/~jaw2u

Menu What are exceptions? Declaring, using, and handling exceptions Exceptions in specifications Defensive Programming 26 September 2002 CS 201J Fall 2002

What is an exception? public class AverageLength { public static void main (/*@non_null@*/ String args[]) { String filename = args[0]; … } > javac AverageLength.java > java AverageLength Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at AverageLength.main(AverageLength.java:7) 26 September 2002 CS 201J Fall 2002

What happened? We called the program with no arguments, so the args[] array is empty We then tried to access args[0] Does it make sense to ask for the first element of an empty array? 26 September 2002 CS 201J Fall 2002

Exceptions An exception indicates that something abnormal has happened This could mean an error in the program But not necessarily: It could represent an undefined value of a method call It could indicate some other special condition, such as FileNotFoundException 26 September 2002 CS 201J Fall 2002

Handling Exceptions If an exception occurs, and we don’t do anything about it, the program stops. This isn’t always what we want: If there is an error, we may be able to fix it, report it, or degrade gracefully If there is some other special condition, we may need to take note of this and continue processing 26 September 2002 CS 201J Fall 2002

Try and Catch The try clause indicates what to attempt to do file = new FileReader(filename); } catch (FileNotFoundException e) { System.out.println(“Could not open “+filename); System.exit(1); } The try clause indicates what to attempt to do The catch clause specifies: An exceptional case What to do if that exceptional case occurs 26 September 2002 CS 201J Fall 2002

Try and Catch If the try clause finishes normally file = new FileReader(filename); } catch (FileNotFoundException e) { System.out.println(“Could not open “+filename); System.exit(1); } If the try clause finishes normally The catch clause is ignored If the try clause throws an exception, The system looks for a matching catch clause If one exists, it is executed, i.e. it handles the exception 26 September 2002 CS 201J Fall 2002

Throwing Exceptions Some operations in Java generate exceptions automatically We can also throw exceptions explicitly: public float sqrt(float value) { if (value < 0.0) { throw new Exception(“Value is negative”); } else { ... } 26 September 2002 CS 201J Fall 2002

Exception Propagation public first_method() { try { second_method(); } catch (MyException e) { System.out.println( “A MyException occurred”); } public second_method() { try { throw new MyException(); } catch (SomeOtherException e) { System.out.println( “An exception occurred”); } What should happen here? 26 September 2002 CS 201J Fall 2002

Exception Propagation public first_method() { try { second_method(); } catch (MyException e) { System.out.println( “A MyException occurred”); } public second_method() { try { throw new MyException(); } catch (SomeOtherException e) { System.out.println( “An exception occurred”); } first_method calls second_method second_method throws a MyException The catch clause in second_method does not match The catch clause in first_method does match The handler for MyException in first_method is executed to handle the exception 26 September 2002 CS 201J Fall 2002

Exception.printStackTrace() When an exception occurs, we can call e.printStackTrace() to find out what happened: try { int a[] = new int[10]; a[17] = 1; } catch (Exception e) { System.err.println(e.toString()); e.printStackTrace(); } java.lang.ArrayIndexOutOfBoundsException at foo.main(foo.java:5) 26 September 2002 CS 201J Fall 2002

Declaring our own exceptions We can also declare our own exception types: public class MyException extends Exception { } Why would we do this? If a method is not defined for all cases, it makes sense to throw an exception rather than a meaningless value It allows a program to indicate the nature of an error It allows the program to indicate special, but non-error conditions 26 September 2002 CS 201J Fall 2002

Example class ElementNotFoundException extends Exception { } class IntList { int array[]; int n; public int getElementIndex(int element) throws ElementNotFoundException { for (int i=0; i<array.length; i++) { if (array[i] == element) { return i; } throw new ElementNotFoundException(); 26 September 2002 CS 201J Fall 2002

Checked vs. Runtime Exceptions Checked exceptions must be caught in a try..catch, or explicitly propagated: public int getIndex(String element) throws ElementNotFoundException { ... } The Java compiler enforces this Java does not require RuntimeExceptions to be declared, but it is a good idea ESC/Java does require this 26 September 2002 CS 201J Fall 2002

Exception Type Hierarchy Throwable Error Exception RuntimeException We can add our own exceptions to the hierarchy when we declare them: class MyRuntimeException extends RuntimeException { } 26 September 2002 CS 201J Fall 2002

Generic Catch Clauses A catch clause can match subtypes of exceptions: public class GeneralException extends Exception { } public class SpecificException extends GeneralException { } ... try { throw new SpecificException(); } catch (GeneralException ge) { ge.printStackTrace(); } 26 September 2002 CS 201J Fall 2002

Built-in Exception Types Checked Exceptions: FileNotFoundException IOException EndOfFileException Runtime Exceptions: ArrayIndexOutOfBoundsException NullPointerException 26 September 2002 CS 201J Fall 2002

Exceptions in Abstractions The exceptional behavior of a method is part of the abstraction it implements The kinds of exceptions a method might throw, and what they mean, are just as important to understand as the normal return value What could happen if we use a method, but don’t understand what exceptions it might throw, and don’t handle them? 26 September 2002 CS 201J Fall 2002

Unhandled Runtime Exceptions The Ariane V 26 September 2002 CS 201J Fall 2002

Exceptions in Specifications Java requires us to declare checked exceptions in a method’s throws clause ESC/Java requires both checked and runtime exceptions to be declared ESC/Java can be used to prove that certain runtime exceptions are not possible ESC/Java annotations can be used to specify what should be true when an exception is thrown 26 September 2002 CS 201J Fall 2002

Proving Absence of Exceptions public int getElementIndex(int array[],int element) //@ requires array != null { for (int i=0; i<array.length; i++) { if (array[element] == i) { return i; } Without this, ESC/Java issues a warning: Warning: possible null dereference (Null) for (int i=0; i < array.length; i++) { ^ 26 September 2002 CS 201J Fall 2002

Defensive Programming It is better to catch errors early We can catch errors early if we add extra checks to the program for things that should not happen We can use exceptions to do this 26 September 2002 CS 201J Fall 2002

Checking Requirements We can verify the precondition of a method and throw an exception if it fails: public int getIndex(int array[], int element) throws PreconditionNotMetException //@ requires array != null //@ ensures array[\result] == element { if (array == null) { throw new PreconditionNotMetException(“array != null”); } else { ... } 26 September 2002 CS 201J Fall 2002

Checking Invariants We can also check a rep invariant and throw an exception if it fails: public class IntList { int array[]; int n; //@ invariant array != null && 0 <= n && n <= array.length public void addElement(int new_element) { if (array == null || n < 0 || n > array.length) { throw new InvariantFailureException(); } .... 26 September 2002 CS 201J Fall 2002

Summary Exceptions indicate abnormal or special conditions in a program Exceptions propagate up the call chain until a matching handler is found Exceptions are objects Exceptional cases are part of the abstraction, and should be part of specifications Exceptions can be used in defensive programming to catch mistakes early 26 September 2002 CS 201J Fall 2002

Charge Coach Dave will have office hours on Friday from 3:30 to 4:30pm to give back design documents for PS4 and answer any questions about them 26 September 2002 CS 201J Fall 2002