CS1101: Programming Methodology Recitation 7 – Exceptions

Slides:



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

Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
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.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
Chapter Chapter 8 Exceptions and Assertions.
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.
Exception handling Dealing with life’s little surprises.
©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.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
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.
Ahmad Al-Rjoub Chapter 6 Exceptions CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
CS1101: Programming Methodology Aaron Tan.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
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.
Java Exception Handling Handling errors using Java’s exception handling mechanism.
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.
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.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
CS1101X: Programming Methodology Recitation 5 Exceptions & Characters and Strings.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling.
Exceptions In this lecture:
Recitation 2 Exception handling.
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Objectives You should be able to describe: Interactive Keyboard Input
Exceptions and User Input Validation
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Introduction to OO Program Design
COMPSCI 230 S Programming Techniques
Handling Exceptions.
EE422C Software Implementation II
Exceptions & exception handling
Exceptions & exception handling
Exception Handling in Java
Exception Handling in Java
Lecture 11 Objectives Learn what an exception is.
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.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
Exceptions.
Tutorial MutliThreading.
Java Basics Exception Handling.
Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e
CIS 110: Introduction to Computer Programming
Java Exception Handling
Presentation transcript:

CS1101: Programming Methodology Recitation 7 – Exceptions CS1103 Digital Logic Design CS1101: Programming Methodology Recitation 7 – Exceptions

Exception Handling Program correctness Program robustness/reliability Guarantees correct results for all valid input Program robustness/reliability Ability to run under various conditions Does not crash when wrong type of argument is passed to method or invalid input valid is entered Use mechanism called exception handling

Catching Exceptions Case Study: Age Input An error condition occurs during the normal course of program execution Exception is thrown Exception handling routine is executed Exception is caught Case Study: Age Input

Version 1 - No exception handling import java.io.*; import java.lang.*; import java.util.*; class AgeInputVer1 { private static final String DEFAULT_MESSAGE = "Your age:"; public AgeInputVer1() { } public int getAge() throws IOException { return getAge (DEFAULT_MESSAGE); public int getAge(String prompt) throws IOException { BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); System.out.println (prompt); int age = Integer.parseInt (stdin.readLine()); return age;

What happens if user spells out age, e.g. nine, instead of 9 ? Program gets a person’s age and outputs the year in which the person was born. public class AgeInputMain { public static void main(String[] args) throws IOException { Calendar today = Calendar.getInstance(); int age, thisYear, bornYear, answer; AgeInputVer1 input = new AgeInputVer1(); age = input.getAge ("How old are you ?"); thisYear = today.get (Calendar.YEAR); bornYear = thisYear - age; System.out.println ("You are born in " + bornYear); } What happens if user spells out age, e.g. nine, instead of 9 ?

AgeInputVer1 What happens if user spells out age, e.g. nine, instead of 9 ? A number format exception is thrown Input value nine cannot be converted to an integer by using parseInt method. System will handle the thrown exception by displaying the error message java AgeInputMain How old are you ? nine Exception in thread "main" java.lang.NumberFormatException: For input string: "nine" > at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:468) at java.lang.Integer.parseInt(Integer.java:518) at AgeInputVer1.getAge(AgeInputMain.java:24) at AgeInputMain.main(AgeInputMain.java:35)

Version 2 – Loop until valid input public class AgeInputVer2 { private static final String DEFAULT_MESSAGE = “Your age: ”; public AgeInputVer2() { } public int getAge() throws IOException { return getAge (DEFAULT_MESSAGE); public int getAge(String prompt) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); int age; while (true) { System.out.println (prompt); String inputStr = stdin.readLine(); try { age = Integer.parseInt (inputStr); return age; // input OK, return value and exit } catch (NumberFormatException e) { System.out.println (“Input is invalid. Please enter digits only”); Need to specify which exception we are catching

AgeInputVer2 Loop until valid input java AgeInputMain How old are you ? nine Input is invalid. Please enter digits only ten 10 You are born in 1994

Version 3 – Catch invalid negative integer public class AgeInputVer3 { private static final String DEFAULT_MESSAGE = “Your age: ”; public AgeInputVer3() { } public int getAge() throws IOException { return getAge (DEFAULT_MESSAGE); public int getAge(String prompt) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); int age; while (true) { System.out.println (prompt); String inputStr = stdin.readLine(); try { age = Integer.parseInt (inputStr); if (age < 0) { throw new Exception(“Negative age is invalid”); return age; } catch (NumberFormatException e) { System.out.println (“Input is invalid. Please enter digits only”); } catch (Exception e) { System.out.println (“Error: ” + e.getMessage()); Version 3 – Catch invalid negative integer Multiple catch blocks; checked in sequence List more specialized exceptions first

AgeInputVer3 Catch invalid negative integer java AgeInputMain How old are you ? twelve Input is invalid. Please enter digits only -12 Error: Negative age is invalid 12 You are born in 1992

AgeInputVer3 What happens if we reverse the order of the catch blocks ? try { … } catch (Exception e) { } catch (NumberFormatException e) { } Second catch block will never be executed because any exception object will match the first catch block.

AgeInputVer4 Restrict valid input by specifying lower and upper bounds Client specify lower and upper bound as the time of object creation AgeInputVer4 input = new AgeInputVer4 (10, 20); How should getAge respond when input is outside the range of client designated lower and upper bounds ? Instead of catching it, getAge should propagate the thrown exception back to caller (client) to handle since the condition is set by the client. Don’t catch an exception that is thrown as a result of violating the condition set by client programmer. Propagate the exception back to client programmer’s code to handle

Version 4 – Restrict valid input by specifying lower and upper bounds public class AgeInputVer4 { 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 int lowerBound; private int upperBound; public AgeInputVer4() { setBounds (DEFAULT_LOWER_BOUND, DEFAULT_UPPER_BOUND); } public AgeInputVer4(int low, int high) throws IllegalArgumentException { if (low > high) { throw new IllegalArgumentException (“lower bound is higher than upper bound”); } else { setBounds (low, high); private void setBounds (int low, int high) { lowerBound = low; upperBound = high;

Version 4 – Restrict valid input by specifying lower and upper bounds public int getAge() throws Exception { return getAge (DEFAULT_MESSAGE); } public int getAge(String prompt) throws Exception { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); int age; while (true) { System.out.println (prompt); String inputStr = stdin.readLine(); try { age = Integer.parseInt (inputStr); if (age < lowerBound || age > upperBound) { throw new Exception(“Input out of bound”); return age; } catch (NumberFormatException e) { System.out.println (“Input is invalid. Please enter digits only”); Propagate exception No catch block for Exception

AgeInputVer4 Don’t catch an exception that is thrown as a result of violating the condition set by client programmer. Propagate the exception back to client programmer’s code to handle java AgeInputMain How old are you ? twelve Input is invalid. Please enter digits only 5 Exception in thread "main" java.lang.Exception: Input out of bound at AgeInputVer4.getAge(AgeInputMain.java:122) at AgeInputMain.main(AgeInputMain.java:139)

AgeInputVer4 If client specify lower and upper bound at the time of object creation as AgeInputVer4 input = new AgeInputVer4 (20, 10); java AgeInputMain Exception in thread "main" java.lang.IllegalArgumentException: lower bound is higher than upper bound at AgeInputVer4.<init>(AgeInputMain.java:96) at AgeInputMain.main(AgeInputMain.java:138)