DOC PREVIEW
Berkeley COMPSCI 61B - Lecture Notes

This preview shows page 1-2-3-27-28-29 out of 29 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Slide 1AnnouncementsPackage VisibilityQuizTodayIn a Perfect World …The Bad News…Slide 8Dealing with ExceptionsTypes of ExceptionsTypes of ExceptionsTraditionally…Exception Handling in JavaExceptionsPre-declared SubtypesUnchecked ExceptionChecked ExceptionsThrowing Checked ExceptionsExampleWhen Exceptions are ThrownWhen to Declare ExceptionsThrowing ExceptionsCreating Your Own ExceptionsCatching ExceptionsExampleScoping RulesCatching Multiple ExceptionsfinallyNext TimeCS 61B Data Structures and Programming Methodology July 7, 2008David SunAnnouncements•You’ve started (or finished) project 1, right?Package VisibilitySame Package Subclass Everywherepublic Yes Yes Yesprotected Yes Yes Nodefault Yes No Noprivate No No No• public declarations represent specifications—what clients of a packageare supposed to rely on.• package private declarations are part of the implementation of aclass that must be known to other classes that assist in the implementation.• protected declarations are part of the implementation that subtypesmay need, but that clients of the subtypes generally won’t.• private declarations are part of the implementation of a class thatonly that class needs.Quizpackage SomePack;public class A1 {void f1() {A1 a = ...a.x1 = 3; // OK}protected int y1;private int x1;}//default packageclass 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?}void f1() { //does this //override?}}ERRORERRORERRORERROROKERRORERRORYESToday•Exception HandlingIn 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. IOExceptionUnchecked 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: NullPointerExceptionChecked 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: InterruptedExceptionThrowing 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.Exampleclass 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 exceptionWhen 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


View Full Document

Berkeley COMPSCI 61B - Lecture Notes

Documents in this Course
Lab

Lab

4 pages

Matrix

Matrix

3 pages

Numbers

Numbers

14 pages

Lectures

Lectures

12 pages

Project 1

Project 1

24 pages

Exam

Exam

8 pages

Load more
Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?