Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fundamental Error Handling

Similar presentations


Presentation on theme: "Fundamental Error Handling"— Presentation transcript:

1 Fundamental Error Handling
Phil Tayco San Jose City College Slide version 1.1 Updated Nov. 5, 2018

2 Error Handling Consider the following. There are at least 2 potential run-time errors that can occur here: public static int findQuotient(int n, int d) { return n / d; } public static void main(String[] args) Scanner input = new Scanner(System.in); System.out.print("Enter numerator: "); int n = input.nextInt(); System.out.print("Enter denominator: "); int d = input.nextInt(); int q = findQuotient(n, d); System.out.println("Quotient is: " + q);

3 Error Handling The input is expecting to look for integers in the input stream If the user enters alphabetic characters such as “six”, an “InputMismatchException” run time error will occur Also, if the user enters integers for n and d, but d is zero, a “ArithmeticException” run time error will occur These are events triggered by the user synchronously, meaning they can occur at specific lines of code being executed (“nextInt” or “n / d” for examples) As such, they can be handled with if statements in the code That works for the division by zero, but nextInt is a bit harder since that is code written for us by Java (the issue occurs within nextInt which we cannot see)

4 Error Handling An alternative viewpoint is to look at the areas where a run time error can occur: public static int findQuotient(int n, int d) { return n / d; } public static void main(String[] args) Scanner input = new Scanner(System.in); System.out.print("Enter numerator: "); int n = input.nextInt(); System.out.print("Enter denominator: "); int d = input.nextInt(); int q = findQuotient(n, d); System.out.println("Quotient is: " + q);

5 Error Handling The lines of code in red are areas where these run time errors can occur. Java allows us to “wrap” this code This wrapping allows us to write code that says “here’s some code that may result in a run time error. If that happens, here’s how to handle it” try { System.out.print("Enter numerator: "); int n = input.nextInt(); System.out.print("Enter denominator: "); int d = input.nextInt(); int q = findQuotient(n, d); System.out.println("Quotient is: " + q); }

6 Error Handling The “try” block wraps the code that tells Java there may be run time errors that can occur here. These errors are called “Exceptions” If an Exception occurs, an Exception object is generated and sent to another block of code after the “try” block called the “catch” block catch (InputMismatchException e) { System.out.println(“Input error. Please use only integers”); } The catch block is entered only if an Exception is generated within a try block

7 Error Handling Multiple catch blocks can be chained if the try block can generate multiple types of Exceptions catch (InputMismatchException e) { System.out.println(“Input error. Please use only integers”); } catch (ArithmeticException e) System.out.println(“Error with numbers”); The key to note here is that these are errors we have decided to handle. We are not putting these “in case the user enters bad data”, we are putting them to “ensure only handling integer data and denominators not equal to 0”

8 Error Handling Notice for the control flow that if an Exception is caught, code execution continues from there – it’s like a “go to” from the area in the try block where the Exception was found to the appropriate catch block where the Exception is caught Once the catch is done, normal program flow resumes after the catch blocks In this example, the effect is an error is handled, but the program ends from there As would normally be handled, keeping the program running if an Exception is found will involve using a loop – the key is putting the loop around the entire try…catch block

9 Error Handling do { try System.out.print("Enter numerator: ");
int n = input.nextInt(); System.out.print("Enter denominator: "); int d = input.nextInt(); q = findQuotient(n, d); continueFlag = false; } catch (InputMismatchException e) System.out.println("Incorrect input error" ); input.nextLine(); catch (ArithmeticException e) System.out.println(e); } while (continueFlag == true); System.out.println("Quotient is: " + q);

10 Error Handling Here, the do…while loop surrounds the try…catch blocks controlling whether or not the process of collecting evaluating user data is correct The “continueFlag” variable (declared before the loop starts) manages the loop – the loop is set to continue until all the code in the try block is executed Notice in the InputMismatchException catch block, there’s an extra “nextLine()” function – this is due to input Scanner object still having a carriage return in its buffer that needs to be cleared so it can read the next line of input (a common issue with String input through the Scanner) Remember this does not mean the code is now foolproof – it only means we have code designed to capture Exceptions we designed to handle

11 The Exception Class The Exception class is actually a superclass in the Exception inheritance hierarchy “InputMismatchException” and “ArithmeticException” objects are types of Exceptions Because they inherit from Exception, it then allows for any catch block that the type of object thrown from a try block is also a type of Exception Put another way, this allows catch blocks to also use a sort of “default” way of catching Exceptions similar to the default case in a switch statement

12 Error Handling catch (InputMismatchException e) {
System.out.println(“Input error. Please use only integers”); } catch (Exception e) System.out.println(“Exception: ” + e); Here, the last possible type of Exception that can be caught is the superclass Exception object Any type of Exception that gets thrown in a try block now has a “default” catch block if any of the other catch blocks do not catch the type thrown In this example, if an unforeseen Exception such as “RunTimeException” is thrown, the last catch block will catch it polymorphically

13 The Exception Class The default catch Exception block is useful in case an unforeseen Exception is thrown As good practice, since you are already setting up the code infrastructure to do a try…catch set, it is helpful to have a last catch block for the generic Exception class as a last resort try…catch should still be used to identify catching known Exceptions. Default Exceptions are best used for backup purposes

14 Summary The text goes into more detailed extent on the use of try…catch as well as another clause, “finally” Exceptions are also classes so it is possible to define your own Exception subclasses Methods can also be designed to “throws” specific Exceptions Best practice is to try and define through requirements what types of issues you want your program to handle and use code (try…catch or if…else statements) to address them try…catch is nice because it can structurally handle multiple potential issues in a set of code Use exception handling as often as possible but only do so as required for as much as one can foresee


Download ppt "Fundamental Error Handling"

Similar presentations


Ads by Google