(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
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.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
(c) University of Washington11-1 CSC 143 Java More on Exceptions Reading: Ch. 15.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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 Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
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.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Object Oriented Programming
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
COMP Exception Handling Yi Hong June 10, 2015.
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.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
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.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
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.
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.
Java Exceptions a quick review….
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Chapter 12 Exception Handling
Exception Handling.
CSE 143 Java Exceptions 1/18/2019.
Exceptions 19-Feb-19.
Exceptions 7-Apr-19.
CMSC 202 Exceptions 2nd Lecture.
CSC 143 Java More on Exceptions.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
CSC 143 Java Errors and Exceptions.
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Exceptions 5-Jul-19.
Exception Handling.
Presentation transcript:

(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15

(c) University of Washington10-2 What Can Go Wrong With Programs? Programs can have bugs and try to do things they shouldn't. E.g. try to send a message to null Users can ask for things that they shouldn't (we can't control the user). E.g. try to withdraw too much money from a bank account The environment may not be able to provide some resource that is needed Program runs out of memory or disk space Expected file is not found Extreme network examples: Thousands to millions of tiny sensors (one or more sensors break down) Interplanetary Internet (a server is down)

(c) University of Washington10-3 Coping Strategies Check all user input! (Not doing this has led to many insecurities.) But what should the program do if it's wrong? Be able to test whether resources were unavailable. But what should the program do if they weren't? Other strategies?

(c) University of Washington10-4 Reporting Errors with Status Codes If a method cannot complete properly because of some problem, how can it report it to the rest of the program? One approach: return a status code ( error code) Boolean status flags are very common A boolean flag: true means OK, false means failure Integers or other types could be used An integer flag: 0 means OK, 1 means error of kind #1, etc. For object return types: null could mean error, non-null could mean success What's bad about using this idea of returning a status code?

(c) University of Washington10-5 Status Codes in BankAccount From the original design of the bank account operations: public boolean deposit (double amount) { return this.updateBalance(amount); } public boolean withdraw(double amount) { return this.updateBalance(-amount); } private boolean updateBalance(double amount) { if (this.balance + amount < 0) { System.out.println("Sorry, you don't have that much money to withdraw."); return false; } else { this.balance = this.balance + amount; return true; } What do you think?

(c) University of Washington10-6 Status Codes: Pro and Con Easy to program, in the method that detects the error MyObject methodThatMightFail(…) { … if (weirdErrorCondition()) { return null; } else { //continue and create an object to return … } Can be bothersome for callers (why?) Can be unreliable (why?)

(c) University of Washington10-7 An Alternative: Throwing Exceptions Java (and C++, and many modern languages) include exceptions as a more sophisticated way to report and handle errors If something bad happens, program can throw an exception A throw statement terminates the throwing method throw sends back a value, the exception itself. So far it sounds a lot like the return statement A return statement terminates the method return can send a value back to the caller

(c) University of Washington10-8 Revised BankAccount Methods public void deposit (double amount) { this.updateBalance(amount); } public void withdraw(double amount) { this.updateBalance(-amount); } private void updateBalance(double amount) { if (this.balance + amount < 0) { throw new IllegalArgumentException("insufficient funds"); } else { this.balance = this.balance + amount; } Methods now have void return type, not boolean Error message and "return false" replaced with throw of new exception object Callers can chose to ignore the exception, if they don't know how to cope with it It will be passed on to the caller's caller, and so on, to some caller that can cope

(c) University of Washington10-9 Return vs Throw A return takes the execution right back to where the method was called Sometimes referred to as the "call site" A throw takes the execution to code (the handler) designated specifically to deal with the exception The handler is said to catch the exception The handler might not be at or near the call site The calling (client) module might not even have a handler If a handler doesn't exist somewhere, the program aborts

(c) University of Washington10-10 Throw Statement Syntax To throw an exception object, use a throw statement Syntax pattern: throw ; The expression must be an object of type throwable There are many such classes already defined BankAccount example used IllegalArgumentException The expression can't be omitted But it doesn't just return to the caller, but ends execution of the caller, and its caller, and so on, until a handler is found (explained later), or the whole program is terminated It's bad practice for a complete program to die with an unhandled exception

(c) University of Washington10-11 Exception Objects In Java Exceptions are regular objects in Java Exception are subclasses of the predefined Throwable class Some predefined Java exception classes: RuntimeException (a very generic kind of exception) NullPointerException IndexOutOfBoundsException ArithmeticException (e.g. for divide by zero) IllegalArgumentException (for any other kind of bad argument) Most exceptions have constructors that take a String argument

(c) University of Washington10-12 Throwable/Exception Hierarchy Throwable ErrorException RuntimeException ArithmeticException NullPointerException IllegalArgumentException...

(c) University of Washington10-13 What about Handlers? As we said, return and throw have some similarities When a method ends as a result of a throw... If the caller has a handler, that's where execution continues If the caller doesn't have a handler, then its caller is checked to see if there is a handler. This checking of callers proceeds up the line, until a handler is found; if there isn't one anywhere, the program aborts. That's the big picture. A few details later.

(c) University of Washington10-14 Specifying an Exception Handler If a caller knows how to cope with an exception, then it can specify an appropriate handler using a try-catch block try { mySavingsAccount.withdraw(100.00); myCheckingAccount.deposit(100.00); } catch (IllegalArgumentException exn) { System.out.println("Transaction failed: " + exn.getMessage()); } The catch part of the block constitutes the handler. If an exception is thrown anywhere inside the body of the try block, that is an instance of IllegalArgumentException or a subclass, then the exception is caught and the catch block is run

(c) University of Washington10-15 Try-Catch Blocks: Syntax Syntax: try { } catch ( ) { } catch ( ) { } … Can have one or more catch clauses for a single try block

(c) University of Washington10-16 Try-Catch Blocks: Semantics First evaluate If no exception thrown during evaluation of body, or all exceptions that are thrown are already handled somewhere inside body, then we're done with the try-catch block; skip the catch blocks Otherwise, if an exception is thrown and not handled, then check each catch block in turn See if the exception is an instance of If so, then the exception is caught: Bind to the exception; execute ; skip remaining catch blocks and go to the code after the try-catch block If not, then continue checking with the next catch block (if any) If no catch block handles the exception, then continue searching for a handler, e.g. by exiting the containing method and searching the caller for a try-catch block surrounding the call

(c) University of Washington10-17 Example Implement a robust transferTo method on BankAccount, coping properly with errors that might arise public class BankAccount { … public void transferTo(BankAccount otherAccount, double amount) {