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.

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.
Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
COMP 121 Week 5: Exceptions and Exception Handling.
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.
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.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
For use of Cleveland State's IST410 Students only 1 Exception.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,
(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.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
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 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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
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.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
CIS 270—Application Development II Chapter 13—Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
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.
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.
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.
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.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
(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 and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
MIT AITI 2003 Lecture14 Exceptions
CS102 – Exceptions David Davenport Latest: May 2015
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Handling Exceptions.
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 25-Apr-19.
Exceptions 22-Apr-19.
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.
Exceptions 5-Jul-19.
Exception Handling.
Presentation transcript:

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 its sub-classes default = accessible to classes in same “package” * Java Spec (sec ) A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object. Specifierclasssubclasspackageworld privateX protectedX X*X publicXXXX packageXX

2 LockPick Take Two class XBox implements LockBox { protected boolean open; … } class LockPick extends LockBox { public static void openXBox(XBox x) { x.open = true; // only if LockPick in same package } } XBox x = new XBox(…) LockPick.openXBox(x);

3 Exceptions Weiss sec. 2.5

4 Errors What to do when errors are encountered? import java.io.PrintStream; class DangerMouse { public static void main(String args[]) { printOneInteger(args, System.out); } public static void printOneInteger(String args[], PrintStream out) { System.out.println("got: " + getOneInteger(args);); } public static int getOneInteger(String args[]) { return Integer.parseInt(args[0]); }

5 Avoiding Errors What to do when errors are encountered? Idea #1: Avoidance –Add checks before “dangerous” operations –Don’t do anything that will (might) fail –Too many checks! –What to do when a check fails? Idea #2: Avoidance + Error Codes –Add checks after “fallible” operations too –If errors encountered, return some kind of error code –Too many checks! –Clumsy, error-prone, confusing

6 Ugly Code public static void printOneInteger(String args[], PrintStream out) { int i = getOneInteger(args); if (i % 2 == 0) i = i / 2; else return -1; // some kind of error in args if (!checkForEnoughMemory(5 + 10)) return -2; // hope 10 is enough! String s = "got: " + i; if (s == null) return -4; // something went wrong with allocation if (out == null) return -3; // bad output stream if (out.println(s) < 0) return -5; // something went wrong with output return 0; } // return an 2*integer, or -1 if arg is missing, or -3 if not in right format public static int getOneInteger(String args[]) { if (args == null || args.length == 0) return -1; if (!checkIntegerFormat(args[0]) return -3; return 2*Integer.parseInt(args[0]); }

7 Structured Exception Handling Errors cause programs, even machines, to crash. Can’t avoid all dangerous operations. Goal: –Want “normal case” code should flow nicely –Want to catch exceptional cases, and deal with them separately –Keep information about what went wrong: what kind of exceptional case details about what specifically went wrong where it happened in the code other info particular to this kind of exceptional case –Be able to return this info up the call-chain to whatever method can deal with the problem But don’t interfere with normal return statements! Instead, we say that we “throw” the exceptional case up the call chain

8 Throwable Hierarchy Throwable ErrorException RuntimeException OutOfMemoryError InternalError UnknownError … NullPointerException ArrayIndexOutOfBoundsException ArithmeticException NoSuchElementException ClassCastException … IOException FileNotFoundException ZipException MalformedURLException …

9 Throwable Contains a “stack trace” / “call chain” –which method called which method called … called the method that had a problem Has a String message (some detail about what happened) Can have a Throwable cause (some other error that caused this one) “An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.” (Java Documentation) “The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.”

10 Throwing an Exception class Typo extends Exception {…} static int eval(TreeCell t) throws Typo { String s = t.getElt(); if (s.length() == 0) throw new Typo(“empty token”); if (s.equals(“+”)) return … else if (Character.isLetter(s.charAt(0))) return … else if (Character.isDigit(s.charAt(0))) return … else throw new Typo(“unrecognized operand: “ + s); } Keyword throws tells compiler (and programmer) what exceptions might get thrown by this method Keyword throw takes a Throwable object, aborts the current method (with NO return value!), and passes the Throwable object up the call-chain If s is empty, abort! We create a new Typo object to hold details

11 Propagating an Exception The exception (e.g., Throwable object) passes up the call chain, aborting every method it encounters… abort! void getExpression(BufferedReader in) throws Typo, IOException { String s = in.readLine(); doExpression(s); } void doExpression(String s) throws Typo { TreeCell t = parseExpression(s); int i = eval(t); System.out.println(“eval returned “ + i); } int eval(TreeCell t) throws Typo { … throw new Typo(…); … } abort!

12 Catching an Exception Until it lands inside a try-catch block that specifies the correct type of exception public static void main(String args[]) { try { … getExpression(in); … } catch (Typo te) { System.out.println(“oops: you made a typo “ + te.getMessage()); // other error handling code } catch (IOException ioe) { // more error handling code } void getExpression(BufferedReader in) throws Typo, IOException { String s = in.readLine(); doExpression(s); } Kind of error you want to catchA name for the object that was thrown, and is now caught

13 Control Flow Normal execution (no exceptions thrown): start  body   end // no errors Exception Typo thrown start  part of body  catch-clause  end Exception other than Typo thrown start  part of body  ----  ----  abort! …start… try { … body … } catch (Typo e) { … catch-clause… } …end…

14 Finally Clause Often want to execute certain code no matter what –e.g., close a file, with or without an exception happening Rule: if body begins, then finally-clause will run –if no exceptions, runs after body –if exception is thrown and caught, right after catch-clause –if exception thrown and not caught, runs before propagating the exception up the call chain …start… try { … body … } catch (Typo e) { … catch-clause… } finally { … final-clause…} …end…

15 Checked vs Unchecked Most exception types are checked. If a method body might generate a checked exception, it must either: –Have a try-catch block for that exception type –Declare the exception type in a throws declaration Some exception types are unchecked. These you do not need to catch (unless you want to) or declare. Why the distinction? –Could happen at any time: e.g. OutOfMemoryError –Nearly any line of code could generate one: e.g., NullPointerException –Nothing you could do about it anyway: e.g. InternalError