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

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

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

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

Errors and Exceptions

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

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

ECE 122. Engineering Problem Solving with Java

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

Abstract Classes, Exceptions

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

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

Exception-Handling Overview

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

BBM 102 Introduction to Programming II Spring Exceptions

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

BBM 102 Introduction to Programming II Spring 2017

Chapter 13 Exception Handling

EXCEPTION HANDLING. Summer 2018

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

CS61B Lecture #12. Public Service Announcement. Miscellaneous Topics: What to do About Errors? throw new SomeException (optional description);

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

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

More on Exception Handling

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

CS159. Nathan Sprague

More on Exception Handling

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

Exceptions. CSC207 Winter 2017

Program Correctness and Efficiency. Chapter 2

CS 3 Introduction to Software Engineering. 3: Exceptions

Exceptions in Java

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

Programming II (CS300)

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

EXCEPTIONS. Java Programming

Correctness and Robustness

CSE 331 Software Design & Implementation

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

Programming Languages and Techniques (CIS120)

School of Informatics, University of Edinburgh

Internal Classes and Exceptions

6.Introducing Classes 9. Exceptions

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

Exception Handling Generics. Amit Gupta

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

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:

2.6 Error, exception and event handling

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

Java Loose Ends. 11 December 2017 OSU CSE 1

Fundamentals of Object Oriented Programming

Introduction Unit 4: Input, output and exceptions

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

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

Programming II (CS300)

COMP-202 Unit 9: Exceptions

Check out FilesAndExceptions from SVN. Exam 2 Review File I/O, Exceptions Vector Graphics Project

CSCI 261 Computer Science II

ITI Introduction to Computing II

Exceptions Handling Errors using Exceptions

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

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Exceptions - Example. Exceptions - Example

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

ITI Introduction to Computing II

Data Structures. 02 Exception Handling

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

Checked and Unchecked Exceptions in Java

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

Object Oriented Programming

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

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

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

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

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

Sri Vidya College of Engineering & Technology Question Bank

COMP-202 Unit 9: Exceptions

CS159. Nathan Sprague

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

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

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

Introduction to Computer Science II CS S-22 Exceptions

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

Exceptions and Error Handling

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

Exception Handling. Exception Handling

Programming Language Concepts: Lecture 7

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

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

Object-Oriented Programming Design Topic : Exception Programming

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

Principles of Software Construction: Objects, Design and Concurrency. Exceptions, scope, static data and methods, and Generics.

CS193j, Stanford Handout #25. Exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

14. Exception Handling

Transcription:

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

Announcements You ve started (or finished) project 1, right?

Package Visibility public declarations represent specifications what clients of a package are supposed to rely on. package private declarations are part of the implementation of a class that must be known to other classes that assist in the implementation. protected declarations are part of the implementation that subtypes may need, but that clients of the subtypes generally won t. private declarations are part of the implementation of a class that only that class needs. Same Package Subclass Everywhere public Yes Yes Yes protected Yes Yes No default Yes No No private No No No

Quiz package SomePack; public class A1 { void f1() { A1 a =... a.x1 = 3; // OK protected int y1; private int x1; //default package class A2 { void g (SomePack.A1 x) { x.f1 (); // OK? x.y1 = 3; // OK? class B2 extends SomePack.A1 { void h (SomePack.A1 x) { x.f1 (); //OK? x.y1 = 3; //OK? f1(); // OK? y1 = 3; // OK? x1 = 3; // OK? ERROR ERROR ERROR ERROR ERROR OK ERROR void f1() { //does this YES //override?

Exception Handling Today

In a Perfect World Users would never enter a data of the wrong format. Files they want to open always exist. And code would never have bugs.

The Bad News Exceptional cases will arise, and your will need to handle them. Why? If a user loses all the work she did during a session because of a programming mistake, that user may forever stay away from your program! Professional quality/industrial strength programs devote a large amount of code to handle errors. Safety/mission critical systems depend on the code to do something reasonable in the face of exceptions...

Dealing with Exceptions When an exception occurs, the program ought to either Return to a safe state and allow the user to execute other commands Allow the user to save his/her work and gracefully exit the program. This is not always easy. Exception detection may be needed at multiple places in your code. The code that restores the state of the application can be far removed from where exceptions can occur.

Types of Exceptions External to the program User Input Errors Typos Invalid format: expect a number when text characters are supplied. Device Errors Hardware don t always what you want it to. Printer may be turned off or run out of paper in the middle of a printout. Connection to a remote server may die while your application is receiving data. Physical Limitations Disk running out of space. Run out of available memory.

Types of Exceptions Internal Exceptions: Errors in your code. Accessing an invalid array index. Trying to find an nonexistent entry in a table. Using other methods incorrectly.

Traditionally If a method detected an exception, e.g., an invalid input, the method returns a special error code that the calling method analyzes. Example: A file open method return a 1 if the file cannot be found. Reading the end of a file returns 1 end of file value marker rather than a standard character. What s the drawback?

Exception Handling in Java Java allows every method an alternative exit path if it is unable to complete its task in the normal way. The method throws an object that encapsulates the error. The method exits immediately, no value is returned. The exception handling mechanism looks for an exception handler that can deal with the error condition.

Exceptions Exceptions are objects. All exceptions extend from the Throwable class.

Pre declared Subtypes Error: Internal errors and resource exhaustion inside the runtime environment Usually unrecoverable. Exception: Intended for all other cases. Exceptions that derive from RuntimeException: usually because you made a programming error Others that do not derive from RuntimeException: bad things that happen to a good program, e.g. IOException

Unchecked Exception Intended for programmer Errors If it is a RuntimeExceptions it was your fault! Examples: Executing (String) x when x turns out not to point to a String: ClassCastException Executing A[i] when i is out of bounds: ArrayIndexOutOfBoundsException Executing x.y when x is null: NullPointerException

Checked Exceptions Intended to indicate exceptional circumstances that are not necessarily programmer errors. Examples: Attempting to open a file that does not exist: FileNotFoundException Input or output errors on a file: EOFException Receiving an interrupt: InterruptedException

Throwing Checked Exceptions One way to handle exceptions is to not handle it pass it on and let the user of the code handle it. In this case you advertise that the method can throw an exception. public FileInputStream(String name) throws FileNotFoundException In this example, the constructor can initialize a new FileInputStream object or it can throw an exception if the file specified by the String is not found. public int read() throws IOException In this example, the method can return a byte of data from a FileInputStream or it can throw an exception if some Input Output (IO) error occurs.

Example class MyReader{... public void readsolution() throws FileNotFoundException, IOException { f = new FileInputStream("~cs61b/proj1.solution"); i = f.read();

When Exceptions are Thrown In any of the four situations: 1. You called a method that throws a checked exception. 2. You detected an error and throw a checked exception. 3. An internal error occurs. 4. You made a programming error, causing an unchecked exception

When to Declare Exceptions Cases 1 and 2 are checked exceptions You need to tell the programmers who will use your method about the possibility of an exception: If the exception is not dealt with, the program terminates. Case 3 are errors You do not need to advertise internal Java errors exceptions derived from Error. Any code can throw those exceptions; they are beyond your control. Case 4 are unchecked exceptions You should not advertise unchecked exceptions those that inherit from RunTimeException. These are completely under your control //bad style public void mymethod(int i) throws ArrayIndexOutOfBoundsException

Throwing Exceptions If you detected something that s potentially problematic in your code, you can throw an exception. Example: You have a method that reads a 16 digit credit card numbers. But you get a 12 digit number from the input file. You decide the situation is so abnormal that you want to through an exception. String readbankacctnumber(reader r) throws DataFormatException { while (r.hasnext()) { s = r.next(); if (numberofdigits(s)!= 16) throw new DataFormatException();... return s;

Creating Your Own Exceptions If one of the existing exception classes works for you, then just instantiate an exception object and throw it. Otherwise, you can create your own: class AccountNumberFormatException extends DataFormatException { public AccountNumberFormatException (){ public AccountNumberFormatException (String error) { super(error); A convention to have two constructors: One takes no parameters, and one takes an error message in the form of a String. if (numberofdigits(s)!= 16) throw new AccountNumberFormatException ( ERROR: Account number not 16-digits );

Catching Exceptions When an exception is thrown by a method, the calling method can either catch the exception or keep propagating it (by throwing). If the exception doesn t get handled by anyone, Java will try to handle it: terminate your program and print a stack trace. To catch an exception, set up a try/catch block try { Stuff that might throw exception; Other code; catch (SomeException e) { Handler: do something reasonable; Go on with life;

Example class MyReader{... public void readsolution() throws FileNotFoundException, IOException { f = new FileInputStream("~cs61b/proj1.solution"); i = f.read(); class MyReader{... public void readsolution() try { f = new FileInputStream("~cs61b/proj1.solution "); i = f.read(); catch (FileNotFoundException e1) { whine("foiled!!"); catch (IOException e2) { f.close();

Scoping Rules class MyReader{... public void readsolution() try { FileInputStream f = new ("~cs61b/proj1.solution "); i = f.read(); catch (FileNotFoundException e1) { whine("foiled!!"); catch (IOException e2) { f.close(); f is only visible in the try block. FileInputStream

Catching Multiple Exceptions You can catch multiple exception types: try { Stuff that might throw exception; Othercode; catch (ExceptionType1 e) { Handler: do something reasonable; catch (ExceptionType2 e2) { Handler: do something reasonable; catch (ExceptionType3 e3) { Handler: do something reasonable; Go on with life; The order in which the exception are processed matters: ExceptionType1 needs to be less general than ExceptionType2. You need to catch a FileNotFoundException object before catching an IOException object and before you catch a Exception object. You can catch the most general exception with catch (Exception e) But you have less control on how to process the Exception

finally When the code throws an exception, execution transfers to the exception handler or if no exception handler is found the method exits. What if you want to clear up resources? You put all the cleaning up code in the finally clause: try { Stuff that might throw exception; Othercode; catch (SomeException e) { Handler: do something reasonable; catch (SomeOtherException e2) { Handler: do something reasonable; catch (SomeMoreException e3) { Handler: do something reasonable; finally { Release all resources, e.g. close files and network connections Go on with life;

Next Time Reading Head First Java, pp. 315 338 Next Time: Inner classes Object Cloning Loose Ends