Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
Advertisements

CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
Exception Handling and Format output
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Improve the reliability.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Chapter Chapter 8 Exceptions and Assertions.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
Exception handling Dealing with life’s little surprises.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions Handling.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions and Assertions Animated Version.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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 and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the.
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.
Chapter 12: Exception Handling
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
CS1101X: Programming Methodology Recitation 5 Exceptions & Characters and Strings.
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 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.
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.
DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling.
Chapter 10 – Exception Handling
CS1101: Programming Methodology Recitation 7 – Exceptions
Exception Handling and Format output-CS1050-By Gayani Gupta
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
Exception Handling Contents
Java Basics Exception Handling.
Presentation transcript:

Exceptions Ensuring program reliability

Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces correct results for valid inputs A related concept is program reliability; this is a measure of how well a program performs under a variety of conditions (including invalid inputs) –A program can be correct, but not reliable –A program can be reliable, but not correct –Our goal is to produce programs with both these qualities

Ensuring reliability We do our best to ensure program correctness through a rigorous testing and debugging process To ensure reliability, we must anticipate conditions that could cause problems, and try to deal with them before the problems occur In Java, we have exception handling, a powerful tool for ensuring program reliability

Catching Exceptions An exception represents an error condition that can occur during the normal course of program execution. When an exception occurs, or is thrown, the normal sequence of flow is terminated. The exception-handling routine is then executed; we say the thrown exception is caught.

Catching Exceptions We can increase our programs’ reliability and robustness if we catch the exceptions ourselves using error recovery routines we develop. One way to do this is to wrap the statements that may throw an exception with the try-catch control statement.

Catching Exceptions - example inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); // code that might cause error } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, “” + inputStr +“ is invalid\n” +“Please enter digits only”); }

Catching Exceptions A try-catch block is similar to a selection structure If no error occurs (in the example, if the user entered only digits), the catch block is ignored If there is an error, the catch block executes

Catching Exceptions Statements in the try block are executed in sequence. If more than one exception is possible, multiple catch blocks can be written When one of the statements throws an exception, control is passed to the matching catch block and statements inside the catch block are executed.

Two control flows of the try-catch statement with one catch block.

Catching Exceptions We must specify which exception we are catching in the catch block’s parameter list. In Java an exception is represented as an instance of the Throwable class or its subclasses. The Throwable class has two subclasses: –Error –Exception

Catching Exceptions The Error class represents serious problems that should not be caught by ordinary applications The Exception class represents error conditions that should be caught

Throwable class inheritance hierarchy – a sample

Propagating Exceptions When a method may throw an exception, either directly or indirectly, we call the method an exception thrower. Every exception thrower must be one of two types: –catcher. –propagator.

Propagating Exceptions An exception catcher is an exception thrower that includes a matching catch block for the thrown exception. An exception propagator does not contain a matching catch block. A method may be a catcher of one exception and a propagator of another.

Propagating Exceptions If a method is an exception propagator, we need to modify its header to declare the type of exceptions the method propagates. We use the reserved word throws for this declaration. void C( ) throws Exception {... } void D( ) throws Exception {... }

Propagating Exceptions Without the required throws Exception clause, the program will not compile. However, for the exception of the type called runtime exceptions, the throws clause is optional.

Throwing Exceptions An exception is thrown using the throw statement. throw where is an instance of the Throwable class or its subclasses.

Throwing Exceptions If there is a block of code that must be executed regardless of whether an exception is thrown, we use the reserved word finally. inputStr = JOptionPane.showInputDialog(null, “”); try{ number = Integer.parseInt(inputStr); if (num>100) { throw new Exception(“Out of bound”); } } catch (NumberFormatException e) { System.out.println(“Cannot convert to int”); } catch (Exception e) { System.out.println(“Error: ” + e.getMessage()); } finally { System.out.println(“DONE”); }

Throwing Exceptions When there are multiple catch blocks in a try-catch statement, they are checked in sequence. It is important to check more specialized exception classes before the more general exception classes. When an exception is thrown, its matching catch block is executed and the other catch blocks are ignored.

Catching Exceptions There are two methods of the Throwable class we can call to get information about the thrown exception: –getMessage –printStackTrace

2 possible outcomes of the try-catch statement with multiple catch blocks

Throwing Exceptions If none of the catch blocks matches the thrown exception, the system will search down the stack trace for a method with a matching catch block. If none is found, the system will handle the thrown exception.

Throwing Exceptions Even if there is a return statement inside the try block, the finally block is executed. When the return statement is encountered in the try block, statements in the finally block are executed before actually returning from the method.

2 possible outcomes of the try-catch statement with multiple catch blocks and the finally block

Propagating Exceptions Do not catch an exception that is thrown as a result of violating a condition set by the client programmer. Instead, propagate the exception back to the client programmer’s code and let him or her handle it.

Example // Class to input age: allows client programmers to specify the // lower and upper bounds of acceptable input values import javax.swing.*; class AgeInput { private static final String DEFAULT_MESSAGE = "Your age:"; private static final int DEFAULT_LOWER_BOUND = 0; private static final int DEFAULT_UPPER_BOUND = 99; private static final int DEFAULT_LOWER_BOUND = 0; private static final int DEFAULT_UPPER_BOUND = 99 ; private int lowerBound, upperBound; private void setBounds(int low, int high) { lowerBound = low; upperBound = high; }

Example continued public AgeInput ( ) throws IllegalArgumentException { setBounds(DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND); } public AgeInput (int low, int high) throws IllegalArgumentException { if (low > high) { throw new IllegalArgumentException("Low (" + low + ") was " + "larger than high(" + high + ")"); } else { setBounds(low, high); } public int getAge() throws Exception { return getAge(DEFAULT_MESSAGE); }

public int getAge(String prompt)throws Exception { String inputStr; int age; while (true) { inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); if (age upperBound) { throw new Exception("Input out of bound"); } return age; // input okay so return the value & exit } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "'" + inputStr + " is invalid\n“ + "Please enter digits only"); } // end catch block } // end while loop } // end method } // end class

Types of Exceptions There are two types of exceptions: –Checked. –Unchecked. A checked exception is an exception that is checked at compile time. All other exceptions are unchecked, or runtime, exceptions. As the name suggests, they are detected only at runtime.

Types of Exceptions If a method is a propagator of checked exceptions, the method must have the throws clause. When calling a method that can throw checked exceptions, use the try-catch statement and place the call in the try block, or modify the method header to include the appropriate throws clause. If a method is a propagator of runtime exceptions or errors, the throws clause is optional.

Calling a method that can throw an exception: two options

Calling method that throws a runtime exception – 3 options