1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.

Slides:



Advertisements
Similar presentations
Recitation 4. 2-D arrays. Exceptions. Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] null Assign.
Advertisements

CS April 2010 Exceptions in Java. Read chapter 10. HUMOR FOR LEXOPHILES (LOVERS OF WORDS): Police were called to a day care; a three-year-old was.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
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.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
For use of Cleveland State's IST410 Students only 1 Exception.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
Java Programming Transparency No. 1-1 Java Exception Handling Cheng-Chia Chen.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions Handling.
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. 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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Program Errors Syntax errors Logic errors
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
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.
COMP Exception Handling Yi Hong June 10, 2015.
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.
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.
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
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 and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
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.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Recitation 2 Exception handling.
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Creating and Modifying Text part 2
Exceptions 10-Nov-18.
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.
ATS Application Programming: Java Programming
Chapter 12 Exception Handling
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Chapter 12 Exception Handling and Text IO Part 1
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.
Java Basics Exception Handling.
Presentation transcript:

1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether the YOU would like a lecture that reviews classes, subclasses, inheritance, overriding, constructors, apparent and real types, using some example. Please write your opinion on a blank piece of paper and pass it forward, now. A computer lets you make more mistakes faster than any other invention in history -- with the possible exception of handguns and tequila. Mitch Ratcliffe The essence of immorality is the tendency to make an exception of myself. Jane Addams.

2 Exception handling in Java An exception: something bad or unexpected that happens in a program, e.g. divide by zero subscript out of bounds i/o error null pointer exception no more memory etc. Big problem: where the exception occurs is not always the best place to handle it (see next slide)! Java has special mechanisms for dealing with exceptions: define your own exception throw an exception catch and handle an exception

3 Class Integer has this method: // = the value in s (which should contain a se- // quence of digits, possibly preceded by -). // beginning and trailing whitespace allowed public static int parseInt(String s) int v= Integer.parseInt(“234X4”); Method parseInt doesn’t know how to handle the error; so it should let the caller handle it. But how can it do this without complicating the handling of non-exceptional cases? That’s the question. The answer is: Use Java’s exception-handling mechanism. A case where detection of an error is not the place to handle it

4 // Return the int in integer field f, or 0 if either // f is invalid or the field doesn’t contain an int public static int getIntField(int f) { try { // Store in s the String that is in int field f String s= intFields[f].getText()); return Integer.parseInt(s); } catch (ArrayIndexOutOfBoundsException ex) { return 0; } catch (NumberFormatException ex2) { String t= intFields[f].getText(); intFields[f].setText( t + “not an integer; use 0”); } Example from GUI JLiveWindow normally, just this is executed execute this if f is out of bounds execute this field f did not contain an int

5 Throwing exceptions Divide by zero? Java “throws” an exception: throw new ArithmeticException(“Divide by zero”); IO error? Java “throws” an exception: throw new java.io.IOException(“…”); Integer.parseInt detects that its arg doesn’t contain an int? It “throws” an exception: throw new NumberFormatException(“…”); You, too, can throw exceptions in your program --and you can define your own classes whose instances are exceptions. What is an exception? Who can throw it? What happens when it is thrown? Who catches it?

6 Class Throwable Defined in package java.lang. Has a few more methods besides those show here. An instance of class C can be thrown iff C is a subclass of class Throwable: // Superclass of all errors and exceptions. An instance // contains call stack when it was created and a message. public class Throwable { // Constructor: an instance with message m and // current call stack public Throwable(String m) // Constructor: an instance with no message and // current call stack public Throwable() // = the message of this object (null if none) public String getMessage() // = short description of this instance public String toString() // = same result as getMessage(), if not overridden public String getLocalizedMessage() }

7 The Throwable Hierarchy Throwable Error (not checked --explain later) Internal Error NoClassDefFoundError OutOfMemoryError AWTError StackOverflowError Exception Runtime Exception (not checked --explain later) NullPointerException IllegalArgumentException NumberFormatException ArrayIndexOutOfBoundsException... IOException FileNotFoundException Over 25 Errors and 120 Exceptions come with Java. You can define your own subclasses of Throwable. The non-boldfaced ones are not checked (explain latter) The boldfaced ones are checked (explain later)

8 Class Error Errors that should not be caught!!! Let the system handle them public class Error extends Throwable { // Constructor: an instance with message m and // current call stack public Error(String m) // Constructor: an instance with no message and // current call stack public Error() } public class NoClassDefFoundError extends Error { // Constructor: an instance with message m and // current call stack public NoClassDefFoundError (String m) // Constructor: an instance with no message and // current call stack public NoClassDefFoundError () }

9 Class Exception Errors that you can catch --if you want public class Exception extends Throwable{ // Constructor: an instance with message m and // current call stack public Exception(String m) // Constructor: an instance with no message and // current call stack public Exception() } public class NumberFormatError extends Exception { // Constructor: an instance with message m and // current call stack public NumberFormatError (String m) // Constructor: an instance with no message and // current call stack public NumberFormatError () }

10 Try statement try catch ( … catch ( finally [we don’t discuss this] Need at least one catch clause or the finally clause. To execute, execute the try ; if no exception is thrown, that’s it. If a throw statement is executed: throw new …; the exception is thrown. That’s the end of the try block! Who catches the thrown exception is described on next slide.

11 Propagation of a thrown exception public class C { public static void main(String [] pars { try { … first(); } catch ( XXException ae) { … } } public static void first() { second(); } public static void second() { … throw new XXException(); … } a0 Throwable XXException A statement not in a try-block throws an object. Throw it to calling method. Effect: the call throws the object A statement in a try-block throws an object and a catch clause catches it. That’s it. A statement in a try-block throws an object and no catch clause catches it. It is thrown to try statement itself. Effect: the try-statement throws it. second first main system call stack

12 Example // Read a line from the keyboard and return the integer // on it. If the line does not contain an integer, keeping // asking the user for one until they types one public static int readLineInt() { String s; Read the next line into s; s.trim(); // invariant: input contains the last line read; previous // lines did not contain a recognizable integer while (true) { try { return Integer.parseInt(s); } catch (NumberFormatException ex) { System.out.println(“That wasn’t an integer.” + “Type an integer.”); Read the next line into s; s.trim(); } may throw a NumberFormat Exception

13 The throws clause public static void main(String[] pars) { first(); } public static void first() { throw new Exception(); } Illegal program; won’t compile: Error: Exception java.lang.Exception must be caught or it must be declared in the throws clause of this method (method first). To fix the problem, change method first to: public static void first() throws Exception{ throw new Exception(); } But then method main is illegal and must be changed to public static void main(String[] pars) throws Exception{ first(); } Rule: All checked exceptions (see slide 6) must be caught or mentioned in a throws-clause. Unchecked exceptions need not be mentioned.

14 You are responsible for knowing: About classes Throwable, Error, and Exception. How to write your own subclass of Exception. How to use a try-statement. How an exception propagates up the call chain until it is caught by a catch-clause How to throw an exception using the throw- statement. How to insert a throws-clause. In any culture, subculture, or family in which belief is valued above thought, self-surrender is valued above self-expression, and conformity is valued above integrity, those who preserve their self-esteem are likely to be heroic exceptions. Nathaniel Branden