Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.

Slides:



Advertisements
Similar presentations
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Advertisements

Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
COMP 121 Week 5: Exceptions and Exception Handling.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
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.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch Announcements l Project 6 now out. »Milestone due Oct. 24th »Final project.
Intermediate Java II Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Exception Handling Slides adapted from Prof. Steven Roehrig.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
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.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
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.
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.
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.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
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.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
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.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
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.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
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.
Java Exceptions a quick review….
Exceptions: When things go wrong
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Exceptions 10-Nov-18.
Handling Exceptions.
Exceptions & exception handling
Exceptions & exception handling
Fundamental Error Handling
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws Statement Exception Classes Example: The Debug and AssertionFailure Classes

Programming and Problem Solving With Java 2 Exceptions  Easiest way to write a program  Concentrate on main theme of program, ignoring errors and other exceptional conditions  Add error-handling later  If programming language doesn’t have exceptions  Must intermingle error-handling with main logic  Methods need to return special values to signal error conditions  Makes main logic harder to follow

Programming and Problem Solving With Java 3 Exceptions  Example of error handling without exceptions  sumPositive() method // sumPositive: Returns the sum of the two arguments, or -1 // if either argument is not positive static int sumPositive(int firstValue, int secondValue) { if (firstValue <= 0 || secondValue <= 0) { return -1; } return firstValue + secondValue; }  How to use the method int sum = sumPositive(x, y); if (sum == -1) { System.out.println("Error: x or y is < 0"); } else { System.out.println("The sum is " + sum); }

Programming and Problem Solving With Java 4 Exceptions  Problems  Error handling intermingled with main logic int sum = sumPositive(x, y); if (sum == -1) { System.out.println("Error: x or y is < 0"); } else { System.out.println("The sum is " + sum); }  Programmers can ignore the error code int sum = sumPositive(x, y); System.out.println("The sum is " + sum);  May not be a special value that can be an error code

Programming and Problem Solving With Java 5 Exceptions  Java has exceptions  sumPositive() method now throws an exception // sumPositive: Returns the sum of the two arguments. Throws // Exception if either argument is less than // zero. public static int sumPositive(int first, int second) throws Exception { if (first < 0 || second < 0) { throw new Exception("Param(s) to sumPositive < 0"); } return first + second; }  How to use the method try { int sum = sumPositive(x, y); System.out.println("The sum is " + sum); } catch (Exception e) { System.out.println(e.getMessage()); } Note main logic is together Error handling is here

Programming and Problem Solving With Java 6 Exceptions  Programmer can’t ignore exceptions // testSumPositive: Show that programmer can't ignore exception // thrown from sumPositive() public static void testSumPositive(int x, int y) { int sum = sumPositive(x, y); System.out.println("The sum is " + sum); }  Compiler gives error message Test.java(21,30) : error J0122: Exception 'Exception' not caught or declared by 'void Test.testSumPositive(int x, int y)'  The method must either  Handle the exception (using try & catch), or  Throw the exception  The method can’t simply ignore the exception

Programming and Problem Solving With Java 7 Exceptions: Throwing  A method can throw an exception  Include a throws clause as part of the method’s signature // Demonstration of a program that throws a TurtleException import turtlegraphics.*; public class DemoWithoutTryCatch { public static void main(String[] args) throws TurtleException { Turtle myTurtle = new Turtle(); // Move off the screen (should throw an exception) myTurtle.move(1000); // This never executes System.out.println("Program finished"); }  Exception message TurtleException: Move offscreen at turtlegraphics.Turtle.move(Compiled Code) at DemoWithoutTryCatch.main(DemoWithoutTryCatch.java:14) throws clause

Programming and Problem Solving With Java 8 Exceptions: Throwing  Can throw more than one kind of exception from a method  List them in any order  Put comma between exception names public static void main(String[] args) throws TurtleException, java.io.IOException { // Executable code... }

Programming and Problem Solving With Java 9 Exceptions: Handling  Instead of throwing exception, can handle it in the method  Example  User enters invalid number  Instead of letting program end, catch the exception and let user re-enter the number

Programming and Problem Solving With Java 10 Exceptions: Handling  Catching an exception with try-catch // Demonstration of how to catch an exception import turtlegraphics.*; public class DemoCatchException { public static void main(String[] args) { Turtle myTurtle = new Turtle(); try { // Move off the screen (should throw an exception) myTurtle.move(1000); } catch (TurtleException e) { System.out.println("Caught a TurtleException..."); System.out.println("Message is: " + e.getMessage()); System.out.println("Value is: " + e.getValue()); } System.out.println("Program finished"); }  Program output Caught a TurtleException... Message is: Move offscreen Value is: 1000 Program finished try some code catch exceptions

Programming and Problem Solving With Java 11 Exceptions: Handling  Try-block  Main code logic that might cause an error (exception) try { // Move off the screen (should throw an exception) myTurtle.move(1000); }  Catch-block  Use for error handling catch (TurtleException e) { System.out.println("Caught a TurtleException..."); System.out.println("Message is: " + e.getMessage()); System.out.println("Value is: " + e.getValue()); }  Exception is an object (e in this example)  Use e.getMessage() to get exception’s message  Some exceptions have other methods like getValue()

Programming and Problem Solving With Java 12 Exceptions: Handling  Can have several catch-blocks after a try-block public static void main(String[] args) { Turtle myTurtle = new Turtle(); boolean validDistance; do { validDistance = true; try { int distance = Keyboard.readInt("Amount to move: "); myTurtle.move(distance); } catch (TurtleException e) { System.out.println("Invalid distance - please try again"); validDistance = false; } catch (java.io.IOException e) { System.out.println("Invalid entry - please try again"); validDistance = false; } } while (!validDistance); System.out.println("Program finished"); } Computer checks exceptions in order listed NOTE: List exceptions from most specific to most general Amount to move: 9999 Invalid distance - please try again Amount to move: 100 Program finished

Programming and Problem Solving With Java 13 Exceptions: Propogating  A method that doesn’t handle (catch) an exception passes the exception to its caller

Programming and Problem Solving With Java 14 Exceptions: The finally-block  Make computer execute statements no matter what  Put finally-block after last catch-block  Statements execute whether exception caught or not public static void main(String[] args) { Turtle myTurtle = new Turtle(); try { int distance = Keyboard.readInt("Amount to move: "); myTurtle.move(distance); } catch (TurtleException e) { System.out.println("Invalid distance"); } catch (java.io.IOException e) { System.out.println("Invalid entry"); } finally { System.out.println("Program finished"); } These statements always executed Amount to move: 9999 Invalid distance Program finished Amount to move: 100 Program finished

Programming and Problem Solving With Java 15 Exceptions: The throws Statement  Your methods can throw exceptions  Good for methods with preconditions -- throw exception if precondition not met  Calling method can then decide what to do // sumPositive: Returns the sum of the two arguments. Throws // Exception if either argument is less than // zero. public static int sumPositive(int first, int second) throws Exception { if (first < 0 || second < 0) { throw new Exception("Param(s) to sumPositive < 0"); } return first + second; }  Any method that uses sumPositive() must catch or throw Exception

Programming and Problem Solving With Java 16 Exceptions: Exception Classes  Java’s predefined hierarchy of exception classes Don’t have to catch or throw RuntimeException or descendants

Programming and Problem Solving With Java 17 Exceptions: Exception Classes  To write your own exception class  Extend the Exception class (usually)  Can provide constructors and other methods // Simple exception class that does nothing more than Exception public class MyException extends Exception { // Default constructor public MyException() {} // Constructor with message public MyException(String message) { super(message); }

Programming and Problem Solving With Java 18 Exceptions: Exception Classes // Demonstrate the use of MyExemption, a new subclass of Exception public class MyExceptionDemo { // sumPositive: Returns the sum of the two arguments. Throws // MyException if either argument is less than zero. public static int sumPositive(int first, int second) throws MyException { if (first < 0 || second < 0) { throw new MyException("Param(s) to sumPositive < 0"); } return first + second; } public static void main(String[] args) throws java.io.IOException { try { // First use of sumPositive() should work System.out.println("3 + 4 is " + sumPositive(3, 4)); // Second use should fail System.out.println("3 + (-4) is " + sumPositive(3, -4)); } catch (MyException e) { System.out.println("Caught a MyException exception"); System.out.println("Message is: " + e.getMessage()); System.in.read(); } Example of using new exception class is 7 Caught a MyException exception Message is: Param(s) to sumPositive < 0

Programming and Problem Solving With Java 19 Exceptions: Exception Classes  Can add methods to your exception class that are application-specific // This exception class stores a single integer for // information about the error. public class MyException2 extends Exception { // Constructor with message public MyException2(String message, int badValue) { super(message); this.badValue = badValue; } // getBadValue: Returns the value that caused the problem public int getBadValue() { return badValue; } // Instance variables int badValue; }

Programming and Problem Solving With Java 20 Exceptions: Exception Classes // Demonstrate the use of MyException2 public class MyException2Demo { // sumPositive: Returns the sum of the two arguments. Throws // MyException if either argument is less than zero. public static int sumPositive(int first, int second) throws MyException2 { if (first < 0 || second < 0) { throw new MyException2("Param(s) to sumPositive < 0", Math.min(first, second)); } return first + second; } public static void main(String[] args) throws java.io.IOException { try { // First use of sumPositive() should work System.out.println("3 + 4 is " + sumPositive(3, 4)); // Second use should fail System.out.println("3 + (-4) is " + sumPositive(3, -4)); } catch (MyException2 e) { System.out.println("Caught a MyException exception"); System.out.println("Message is: " + e.getMessage()); System.out.println("Bad value is: " + e.getBadValue()); System.in.read(); } Use new constructor Use new method Example of using new exception class

Programming and Problem Solving With Java 21 Exceptions: Exception Classes  Why write exception classes?  Java’s Exception class carries just one string  Other exception classes can include specific information in the exception object  Can include hints about what caused the error  If more than one thing wrong, can include all the information about what went wrong  Also  Makes program easier to read catch (EmployeeUnderpaidException e)...  versus catch (Exception e)...

Programming and Problem Solving With Java 22 Example: Debug, AssertionFailure  Example of writing and using exception classes:  Debug class  AssertionFailure class  Have used these classes in several programs import Debug; // (Don’t need to import AssertionFailure)... // sumPositive: Returns the sum of the two arguments. public static int sumPositive(int first, int second) { Debug.assert(first >= 0 && second >= 0, "sumPositive(): bad arguments"); return first + second; }  Use of Debug.assert() Debug.assert(condition, message);  If condition is false, assert() throws AssertionFailure exception

Programming and Problem Solving With Java 23 Example: Debug, AssertionFailure  Using Debug.assert() is alternative to exceptions  Can use to make sure program is running correctly, without overhead of throwing exceptions  Advantage: easier to use than exceptions  Disadvantage: can ignore in caller, program then stops with run-time error

Programming and Problem Solving With Java 24 Example: Debug, AssertionFailure  AssertionFailure class // AssertionFailure, a subclass of RuntimeException // (so this exception does not need to be caught or thrown) public class AssertionFailure extends RuntimeException { // Constructor public AssertionFailure(String message) { super(message); }  Debug class // The Debug class, which contains the assert() method public class Debug { // assert: Raises an AssertionFailure exception if the condition // is false public static void assert(boolean condition, String message) throws AssertionFailure { if (!condition) { throw new AssertionFailure(message); } Note: subclass of RunTimeException