Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS1101: Programming Methodology Recitation 7 – Exceptions

Similar presentations


Presentation on theme: "CS1101: Programming Methodology Recitation 7 – Exceptions"— Presentation transcript:

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

2 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

3 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

4 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;

5 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 ?

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

7 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

8 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

9 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

10 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

11 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.

12 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

13 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;

14 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

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

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


Download ppt "CS1101: Programming Methodology Recitation 7 – Exceptions"

Similar presentations


Ads by Google