CSC 143 Java Errors and Exceptions.

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: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
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.
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.
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.
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.
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.
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.
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 and Assertions Chapter 15 – CSCI 1302.
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.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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:
Introduction to Exceptions in Java CS201, SW Development Methods.
Java Exceptions a quick review….
C++ Exceptions.
MIT AITI 2003 Lecture14 Exceptions
Testing and Debugging.
Introduction to Exceptions in Java
Why exception handling in C++?
Introduction to Exceptions in Java
Exceptions and files Taken from notes by Dr. Neil Moore
Chapter 14: Exception Handling
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
Exceptions Handling the unexpected
Chapter 12 Exception Handling
Exceptions and files Taken from notes by Dr. Neil Moore
Exception Handling and Reading / Writing Files
Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Web Design & Development Lecture 7
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.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling and Event Handling
CMSC 202 Exceptions.
Exception Handling.
Throwing, Catching Defining
Presentation transcript:

CSC 143 Java Errors and Exceptions

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)

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?

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? Why? Because the caller has to write code to check for the flag, and typically the caller can't do much but just has to pass the error on to its caller. Also, the method can't return a regular value, if it's return type has been coopted to return a flag instead. It's unreliable because it's easy to forget to check the error code, or think that it couldn't happen.

Status Codes in BankAccount In a BankAccount class that processes banking transactions: 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? What if the caller doesn’t check the console output or the return value? The transaction might appear as successful when it is not. Also, it is bothersome for the caller to check the return value. It makes for long and bulky code (if/else for a simple deposit or withdrawal action)

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?) Why? Because the caller has to write code to check for the flag, and typically the caller can't do much but just has to pass the error on to its caller. Also, the method can't return a regular value, if it's return type has been coopted to return a flag instead. It's unreliable because it's easy to forget to check the error code, or think that it couldn't happen.

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

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

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

Throw Statement Syntax To throw an exception object, use a throw statement Syntax pattern: throw <expression> ; 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

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

Throwable/Exception Hierarchy

As we said, return and throw have some similarities 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.

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

Try-Catch Blocks: Syntax <body, a sequence of statements> } catch (<exception type1> <name1>) { <handler1, a sequence of statements> catch (<exception type2> <name2>) { <handler2, a sequence of statements> … Can have one or more catch clauses for a single try block

Try-Catch Blocks: Semantics First evaluate <body> 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 <exception type1> If so, then the exception is caught: Bind <name1> to the exception; execute <handler1>; 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 Go back to picture of the example try-catch block, and draw pictures of this code calling withdraw, which calls updateBalance, which throws an exception, which exits updateBalance, which exits withdraw, which is then handled by the catch block.

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) {