Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.

Slides:



Advertisements
Similar presentations
Yoshi
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
COMP 121 Week 5: Exceptions and Exception Handling.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
Exceptions and Exception Handling (continued) Carl Alphonce CSE116.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
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
Preventing and Correcting Errors
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
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/
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lec.11 (Chapter 11) Exception Jiang (Jen) ZHENG July 13 th, 2005.
Java Exceptions a quick review….
Exceptions In this lecture:
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Topic: Exception Handling
Introduction to Exceptions in Java
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
Exceptions 10-Nov-18.
Handling Exceptions.
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.
ATS Application Programming: Java Programming
Abdulmotaleb El Saddik University of Ottawa
Exception Handling and Reading / Writing Files
Exception Handling.
Chapter 14 A List ADT.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Web Design & Development Lecture 7
CSE 143 Java Exceptions 1/18/2019.
Chapter 12: Exceptions and Advanced File I/O
CMSC 202 Exceptions 2nd Lecture.
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.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
CSC 143 Java Errors and Exceptions.
Exception Handling Contents
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.
Exceptions 10-May-19.
Presentation transcript:

Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA ‘99 Tutorial; internet notes; notes:H. Conrad Cunningham 5/25/2019 IT350

Exception Handling Exceptions are error conditions -- not bugs a bug is a defect in the code an error condition is a predictable failure that occurs under certain circumstances Exceptions are the way a program can handle gracefully an error that would cause a crash. 5/25/2019 IT350

Exception Handling The Java language provides many exception handlers for programmer errors Java runtime system detects an exceptional event an Exception object is constructed containing info about exception type runtime system throws an exception runtime system looks for code to handle the exception if no handler found, program terminates 5/25/2019 IT350

Exception Handling Example: Java throws an exception when an invalid number is entered public class HandleException { public static void main ( String[] args ) TextReader keyboard = new TextReader(); System.out.println ( “Enter a number: “); String numberString = keyboard.readWord(); double number = Double.parseDouble( numberString ); System.out.println( numberString + “ stored in number as “ + number; ); } 5/25/2019 IT350

Exception Handling Dialogue when number entered is not valid: Java displays a stack of method calls; main is the bottom of the stack the exception occurred in the method on the top Enter a number: 35o Exception in thread “main” java.lang.NumberFormatException: 35o at java.lang.FloatingDecimal.readJavaFormatString (FloatingDecimal.java:1176) at java.lang.Double.parseDouble(Double.java.184) at HandleException.main(HandleException.java.io) 5/25/2019 IT350

Exception Handling We don’t usually want the program to terminate, but rather to proceed with some alternative action in the event of an exception. So we write code to ‘catch’ the exception A ‘try’ block is wrapped around the code being executed. It is followed immediately by a ‘catch’ block, which contains code that executes in the event of an error. We also specify in the catch block what type of exception is being thrown 5/25/2019 IT350

Using try/catch to Handle Exceptions public class HandleException { public static void main ( String[] args ) { TextReader keyboard = new TextReader(); System.out.println ( “Enter a number: “); String numberAsString = keyboard.readWord(); double number; try { number = Double.parseDouble( numberAsString ); } catch (NumberFormatException nfe) System.out.println(numberAsString + “ is not a valid number”); System.out.println(“Setting number to -1.0”); number = -1.0; System.out.println( numberAsString + “ stored in number as “+ number; ); 5/25/2019 IT350

Runtime Exceptions You must know when a method might throw an exception and what type of exception it throws. Read the documentation to find out! /** From Double class: * Return a floating-point number represented by the String * argument; If numberAsString does not represent a valid * number, this method will throw a number format * exception. */ public static double parseDouble(string numberAsString) throws NumberFormatException 5/25/2019 IT350

Handling an I/O Exception If an I/O connection fails, Java throws an IOException. This is the method for a URL connection: public URLConnection() throws IOException Here’s the usage: java.net.URL url = new java.net.URL(“http://www.sice.umkc.edu/”) java.net.URLConnection conn; try { conn = url.openConnection(); } catch ( java.io.IOException e ) { //an error has occurred; log an error, print a message or //throw another exception “If you do not explicitly catch the exception or throw a new exception, the exception will bubble up the stack until it reaches the top or someone finally catches it.” -- Sintes 5/25/2019 IT350

Unchecked Exceptions The parseDouble method does not catch the exception!! If the programmer does not put the method call in a try block and explicitly catch the exception, the program simply terminates (as shown in earlier example). This is one of the “unchecked” exceptions: one that doesn’t need to be handled many unchecked exception classes extend the RuntimeException class. 5/25/2019 IT350

Exceptions Classes Hierarchy Object Handling exceptions in extending classes is optional Throwable Exception Error ClassNotFound Exception IOException RuntimeException ArithmeticException FileNotFound Exception ...EOFException... NumberFormatException IndexOutOfBoundsException NullPointerException ... 5/25/2019 IT350

Writing a Method That Throws an Exception public void deposit (double anAmount ) throws IllegalArgumentException { if (anAmount <= 0.0) throw new IllegalArgumentException(); balance = balance + anAmount; } The keyword ‘throw’ must be followed by an instance of a class that extends Throwable. Because Exception extends Throwable, an instance of any Exception class can be thrown. 5/25/2019 IT350

Multiple Catch Statements There may be multiple categories of exceptions that you want to catch Each category is a separate catch block try { //some code } catch (NullPointerException e1) { … } catch (IllegalArgumentException e2) { … } catch (Exception e3) { //This is a ‘catch-all’ -- catches any type of exception that can be thrown} finally { //this code is executed even if an exception did not occur //commonly used to clean up internal state (like closing a file) If no appropriate catch is found, the exception percolates out of the try statement into any outer try that might have a catch clause to handle it. If a finally clause is present with a try, its code is executed after all other processing in the try is complete. This happens no matter how completion was achieved -- whether through an exception or through a control flow statement such as return or break. Finally clause is commonly used to clean up internal state or to release non-object resources. e.g. finally { if (input != null) input.close(); } 5/25/2019 IT350