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

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

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Yoshi
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
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.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Exceptions and Exception Handling Carl Alphonce CSE116.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions 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.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Chapter 12: Exception Handling
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
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.
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
COMP Exception Handling Yi Hong June 10, 2015.
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.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
Chapter 8-Exception Handling/ Robust Programming.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Geoff Holmes Week 5 problems Handling Throwing Catching Multiple exceptions Finally clause Examples Exception Handling.
Eighth Lecture Exception Handling in Java
Java Exceptions a quick review….
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exception Handling Chapter 9.
Advanced Java Programming
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
Exception Handling.
Presentation transcript:

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

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

Package Visibility Same PackageSubclassEverywhere publicYes protectedYes No defaultYesNo privateNo 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.

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? } void f1() { //does this //override? } ERROR OK ERROR YES

Today Exception Handling

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); } } if (numberOfDigits(s) != 16) throw new AccountNumberFormatException (“ERROR: Account number not 16-digits”); A convention to have two constructors: One takes no parameters, and one takes an error message in the form of a String.

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 FileInputStream("~cs61b/proj1.solution "); i = f.read(); } catch (FileNotFoundException e1) { whine("Foiled!!"); } catch (IOException e2) { f.close(); } f is only visible in the try block.

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 Next Time: – Inner classes – Object Cloning – Loose Ends