CS1110 19 November 2009 Exceptions in Java. Prof. Gries is lecturing in India for the next 7 days or so. Today’s reading: Ch. 10. Next lecture’s reading:

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

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
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.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
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.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
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.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
CS1110 Lec November 2010 Exceptions in Java 1 Reading for today: 10. Next lecture: Ch 9.3 No labs this week, no TA office hours Wed-Fri, see consultant.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CS203 Java Object Oriented Programming Errors and Exception Handling.
CS1101: Programming Methodology Aaron Tan.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
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.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
COMP Exception Handling Yi Hong June 10, 2015.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
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.
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.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
CS April 2008 Exceptions in Java. Today’s reading: Ch. 10. Next lecture’s reading: Ch 17. (Most) on-duty consultants now identifiable by stylish.
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
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.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Question of the Day completes starts  What word completes the 1 st word & starts the 2 nd one: DON???CAR.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
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.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exceptions: When things go wrong
Recitation 2 Exception handling.
ATS Application Programming: Java Programming
Exception Handling and Reading / Writing Files
CMSC 202 Exceptions 2nd Lecture.
Chapter 12 Exception Handling and Text IO Part 1
CSC 143 Java Errors and Exceptions.
Java Basics Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
Presentation transcript:

CS November 2009 Exceptions in Java. Prof. Gries is lecturing in India for the next 7 days or so. Today’s reading: Ch. 10. Next lecture’s reading: sec. 9.3 A7 due Friday December 4. Note the suggested “milestone” timeline (Nov 24: brick rows done; Nov 28: paddle tracks mouse correctly; …) Please check that your grades on CMS match what you think they are. No labs Tuesday Nov 24 or Wed Nov 25; no office hours during Thanksgiving break. There is class Tuesday Nov 24. The final exam will be Monday, Dec. 14 th, 7-9:30pm in Baker Laboratory 200. We are scheduling review sessions for study week, Dec

Today’s (and next lab’s) topic : when things go wrong (in Java) Q1: What happens when an error causes the system to abort? Important example: a “regular person” enters malformed input. Understanding this helps you debug. (NullPointerException, ArrayIndexOutOfBoundsException, …) Q2: Can we make something other than termination happen? It is sometimes better to warn and re-prompt the user than to have the program crash (even if the user didn’t follow your exquisitely clear directions or preconditions). 2 Understanding this helps you write more flexible code.

errors (little e) cause Java to throw a Throwable object as a “distress signal” Errors are signals that things are beyond help. Exceptions are signals that intervention may still be possible; they can be “handled”. Throwable ExceptionError RuntimeException ArithmeticException …… …… OutOfMemoryError … Throwable a0 “/ by zero” detailMessage backtrace … Exception RuntimeException ArithmeticException 3

/** Illustrate exception handling */ public class Ex { public static void first() { second(); } public static void second() { third(); } public static void third() { int x= 5 / 0; } Ex.first(); 4 System prints the call-stack trace on catching exception: Throwable object is thrown to successive “callers” until caught. (In this example, Java will catch it because nothing else does.) AE a0 at Ex.second(Ex.java:9) at Ex.first(Ex.java:5) ArithmeticException: / by zero at Ex.third(Ex.java:13)

Execute the try-block. If it finishes without throwing anything, fine. If it throws an ArithmeticException object, catch it (execute the catch block); else throw it out further. /** = reciprocal(x), or -1 if x is 0*/ public static double ourReciprocal(int x) { return reciprocal(x); } try { } catch (ArithmeticException ae) { return -1; } 5 How can we catch/handle Throwables? With Try/catch blocks. /** = reciprocal of x. Thows an ArithmeticException if x is 0. (Assume this is third-party code that you can’t change.)*/ public static double reciprocal(int x) { …; }

/** = reciprocal(x), or -1 if x is 0*/ public static double ourReciprocal2(int x) { return reciprocal(x); } if (x != 0) { } else { return -1; } 6 Try-statements vs. if-then checking This was meant to be a small example. Use your judgment: For (a small number of) simple tests and “normal” situations that the method itself should handle, if-thens are better. For more “abnormal” situations, try-catches are better. [ In this case, given the specification, if/then is maybe slightly better; anyone reading the code would expect to see a check for 0.] There are some natural try/catch idioms, such as processing malformed user input …

/** Illustrate exception handling (new, more realistic example) */ public class Ex { /** = array of n -1’s. Throws an IllegalArgumentException if n <=0*/ private static int[] initArray(int n) { if (n <= 0) { throw new IllegalArgumentException (“initArray: bad value for n, namely ” + n); } … } java.lang.IllegalArgumentException: initArray: bad value for n, namely -1 at Ex.initArray(Ex.java:20) 7 How can we create our own signals? We can write our own Exception subclasses. We can create new Throwable objects with new statements. Ex.initArray(-1);

We may need a “throws” clause to compile /** Class to illustrate exception handling */ public class Ex2 { public static void first() throws OurException { second(); } public static void second() throws OurException { third(); } public static void third() throws OurException { throw new OurException(“intentional error at third”); } Don’t worry about whether to put a throws clause in or not. Just put it in when it is needed in order for the program to compile. 8