CSE 501N Fall ’09 17: Exception Handling

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

CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
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.
COMP 121 Week 5: Exceptions and Exception Handling.
Chapter 9 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
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.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
Chapter 11  I/O and Exception Handling 1 Chapter 11 I/O and Exception Handling.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Lecture 7 File I/O (and a little bit about exceptions)‏
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.
Applets & Applications CSC 171 FALL 2001 LECTURE 15.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Eleven: Input/Ouput and Exception Handling.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
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.
Chapter 14 Exception Handling. Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
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.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
The Problem Unexpected erroneous situations are often discovered by code which is NOT prepared to remedy the error………. For example.. String in = JOptionPane.showInputDialog(“enter.
Exception Handling.
Eighth Lecture Exception Handling in Java
Java Exceptions a quick review….
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction Exception handling Exception Handles errors
Chapter 12 Exception Handling and Text IO
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Chapter 15 – Exception Handling
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
Exceptions Handling the unexpected
Chapter 12 Exception Handling
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Part B – Structured Exception Handling
Web Design & Development Lecture 7
Chapter 11 Input/Output Exception Handling
Chapter 12: Exceptions and Advanced File I/O
Java Exceptions Dan Fleck CS211.
Exceptions 25-Apr-19.
Tutorial Exceptions Handling.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
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.
Exception Handling.
Presentation transcript:

CSE 501N Fall ’09 17: Exception Handling 03 November 2009 Nick Leidenfrost

Lecture Outline Lab 6 Questions? Exceptions & Errors throws statement Exception Handling: try/catch blocks finally statement

Error Handling: Error Codes Traditional approach: Method returns error code public static final int NO_ERROR = 0; public static final int BAD_INPUT = -1; public static final int INVALID_STATE = -2; // ... public int doSomething (int someInput) { if (!isValidInput(someInput)) return BAD_INPUT; // ... Method body return 0; }

Error Handling: Error Codes Problem: Caller is not forced to check for error code (Failure notification may go undetected) Problem: Calling method may not be able to do anything about failure Caller must also fail and let its caller worry about it Many method calls would need to be checked Lots of special logic would be introduced for handling errors

Error Handling: Error Codes Instead of programming for success: You would always be programming for failure: int theAnswer = x.doSomething(0); IntStorage answer = new IntStorage(0); int errorCode = x.doSomething(0, answer); if (errorCode != x.NO_ERROR) return errorCode;

Error Handling Java provides two ways of dealing with abnormal circumstances: Exceptions “… conditions that a … program might want to catch” Derived from java.lang.Exception Errors “… serious problems that a … program should not try to catch” Derived from java.lang.Error

We throw an exception with the throw clause. Throwing Exceptions Exceptions: Alter control flow to code intended to deal with the problem: Exception handlers Can't be overlooked Java compiler checks for existence of exception handlers Throw an exception object to signal an exceptional condition (or abnormal condition) Example: IllegalArgumentException: Method execution is halted at this point and control flow is returned to the calling method. We throw an exception with the throw clause. // illegal parameter value Exception iaException = new IllegalArgumentException(“Key cannot be null."); throw iaException;

Throwing Exceptions No need to store exception object in a variable: When an exception is thrown, method terminates immediately Execution continues with an exception handler which handles the type of exception that was thrown throw new IllegalArgumentException(“Key cannot be null.“);

Example public class HashMap { public void put (Object key, Object value) { if (key == null) { IllegalArgumentException exception = new IllegalArgumentException(“Key cannot be null.“); throw exception; } // ... } }

Types of Exceptions Two types of exceptions: Checked Unchecked The compiler will check to make sure code exists to handle the exception Unchecked Usually arise in circumstances that would be impossible for the compiler to predict A.k.a. Runtime exceptions [ Eclipse Example ]

Hierarchy of Exception Classes The Hierarchy of Exception Classes

Checked vs. Unchecked Exceptions Usually due to external circumstances that the programmer cannot prevent The compiler checks that you don't ignore them outright You must define exception handlers Mainly occur when dealing with input and output For example, IOException caused by File manipulation, Networking, user input, etc.

Checked vs. Unchecked Exceptions Unchecked Exceptions / Errors: Extend the class RuntimeException or Error They are (usually) the programmer's fault Examples of runtime exceptions: Example of error: OutOfMemoryError NullPointerException ArrayIndexOutOfBoundsException IllegalArgumentException

Checked vs. Unchecked Exceptions Categories aren't perfect: Scanner.nextInt throws unchecked InputMismatchException Programmer cannot prevent users from entering incorrect input This choice makes the class easy to use for beginning programmers Deal with checked exceptions principally when programming with files and streams Coming up in a few lectures… [ Eclipse Scanner Example ]

The throws clause If an exception can be thrown, the compiler will make sure our code acknowledges the exception Two choices: Handle the exception in this method We’ll look at how to do this in a bit… Tell compiler that you want method to be terminated when the exception occurs Use throws keyword to tell Java an exception may be thrown inside the method body that is not handled public void read(String filename) throws FileNotFoundException { FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); . . . }

The throws clause For multiple exceptions: Keep in mind inheritance hierarchy: If method can throw an IOException and FileNotFoundException, only use IOException Better to declare exception than to handle it incompetently public void read(String filename) throws IOException, ClassNotFoundException

Syntax: Exception Specification accessSpecifier returnType methodName(parameterType parameterName, . . .) throws ExceptionClass, ExceptionClass, . . . Example:  public void read(BufferedReader in) throws IOException Purpose: To indicate the checked exceptions that this method can throw

Exception Handlers Catching Exceptions Write exception handlers with the try/catch statement try block contains statements that may cause an exception catch clause contains handler for an exception type

Catching Exceptions: Syntax try { // Code that might cause Exceptions } catch (Exception exception) { // Code to handle Exceptions

Catching Exceptions: control flow Statements in try block are executed If no exceptions occur, catch clauses are skipped If exception of matching type occurs, execution jumps to catch clause If exception of another type occurs, it is thrown until it is caught by another try/catch block

Catching Exceptions: the catch clause catch (IOException exception) { } exception contains reference to the exception object that was thrown catch clause can analyze object to find out more details exception.printStackTrace(): printout of chain of method calls that lead to exception

Catching Errors: the catch clause It is possible to catch Errors, also. Because Errors are typically indicative of more serious problems, doing this is rare. Most often, the program is allowed to terminate. try { ... } catch (Error error) {

Syntax: Multiple catch clauses try { // statement // . . . } catch (ExceptionClass exceptionObject) {

Catching Multiple Types of Exceptions Throws java.lang.IOException try { String filename = “. . .”; FileReader reader = new FileReader(filename); Scanner in = new Scanner(reader); String input = in.next(); int value = Integer.parseInt(input); . . . } Throws java.lang.NumberFormatException catch (Exception exception) { exception.printStackTrace(); } catch (IOException exception) { exception.printStackTrace(); } catch (NumberFormatException exception) { System.out.println("Input was not a number"); }

The finally clause An uncaught exception terminates the current method - ! - This can skip over essential code Example: public void readSomeData () throws IOException { FileReader reader = new FileReader(filename); Scanner input = new Scanner(reader); readData(input); // Can throw an exception reader.close(); // May never get here }

The finally clause We want to execute reader.close() even if an exception happens Use finally clause for code that must be executed "no matter what"

Example: The finally clause FileReader reader = new FileReader(filename); try { Scanner in = new Scanner(reader); readData(in); } catch (IOException ioe) { // ... } finally { reader.close(); // finally clause is executed regardless // of whether exception occurs }

Syntax: The finally clause try { // statements } finally { // Notice that a try block can have a finally clause without a catch // Why is this?

The finally clause Executed when try block is exited in any of three ways: After last statement of try block After last statement of catch clause, if this try block caught an exception When an exception was thrown in try block and not caught For any of these ways, the finally block executes.

Designing Your Own Exception Types You can design your own exception types–subclasses of Exception or RuntimeException Checked Exceptions Unchecked Exceptions if (amount > balance) { throw new InsufficientFundsException( "withdrawal of " + amount + " exceeds balance of “ + balance); }

Designing Your Own Exception Types Make it an unchecked exception–programmer could have avoided it by calling getBalance first Extend RuntimeException or one of its subclasses (InvalidParameterException) Supply two constructors Default constructor A constructor that accepts a message string describing reason for exception

Designing Your Own Exception Types public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException (String message, double shortage) { super(message); } } public class InsufficientFundsException extends RuntimeException { public InsufficientFundsException() {} public InsufficientFundsException (String message) { super(message); } } Your type can include additional information needed to handle properly

Conclusion Questions? Lab 6 Due Tonight at Midnight Lab 7 Assigned Today Due 11/10 at Midnight Lab Now