CS1110 Lec 24 23 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.

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.
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.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
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 Briana B. Morrison CSE 1302C Spring 2010.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
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.
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.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
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:
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
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.
Program Errors Syntax errors Logic errors
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.
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.
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.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
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.
Recitation 2 Exception handling.
Exceptions 10-Nov-18.
ATS Application Programming: Java Programming
Chapter 12 Exception Handling
Exception Handling and Reading / Writing Files
Web Design & Development Lecture 7
Exceptions 10-May-19.
Java Basics Exception Handling.
Presentation transcript:

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 calendar for the updated schedule. There are "labs" next week, but they will serve as office hours plus an optional exercise on exceptions (covered on final). Final: Friday Dec 10 th, 9-11:30am, Statler Auditorium. Register conflicts (same time, or 3 finals in 24 hours) on CMS assignment "final exam conflicts" by Tuesday November 30 th. Please check that your grades on CMS match what you think they are. [For lab-grade issues, contact your lab TA, not the instructors.] A7: remember, "Don't look at any other student/group's code, in any form; don't show any other student/group your code". (The similarity software turned up a few problems on A6, which we are about to start the Academic Integrity violation process for. Note that the checker essentially performs variable-name substitutions, etc., so syntactic modification of the same original program is generally flagged.)

Today’s (and next week's 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 use of the "problem-signaling mechanism" to handle unusual situations in a more appropriate way? 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.

/** Exception example */ public class Ex { public static void first() { second(); } public static void second() { third(); } public static void third() { int x= 5 / 0; } Call: Ex.first(); 3.System prints the call-stack trace: at Ex.second(Ex.java:9) at Ex.first(Ex.java:5) ArithmeticException: / by zero at Ex.third(Ex.java:13) 13 9 line 5 Same structure as our demo: StockQuoteGUI's actionPerformed calls StockQuote's getQuote, which calls In's constructor and readAll methods.

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 4

/** Exception example */ public class Ex { public static void first() { second(); } public static void second() { third(); } public static void third() { int x= 5 / 0; } Call: Ex.first(); 5 In this example, the Java system catches it because nothing else does, it just prints the call-stack trace and aborts. Throwable object --- request for help --- is thrown to successive “callers” until caught by a method that declares that it can provide help. (This is a form of communication between methods.) 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. Assume you can't change this spec. */ public static double ourReciprocal(int x) { return reciprocal(x); } try { } catch (ArithmeticException ae) { return -1; } 6 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; } 7 Try-statements vs. if-then checking The previous slide was just to show try/catch syntax. Use your judgment: For (a small number of) simple tests and “normal” situations, if-thens are usually 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 canonical try/catch idioms, such as processing malformed input.

/** Illustrate exception handling*/ 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) 8 How can we create our own signals? We can create new Throwable objects, via new-statements. We can write our own Exception subclasses (see demo) Ex.initArray(-1);

A technical point: 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. [runtime exceptions don't require a throws-clause; other kinds do] 9 tell the system that an OurException might get thrown