Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Exception Handling Chapter 12 Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully Natural part of the software development process There are two kinds of problems that you may encounter in Java Exceptions – events that signal an unusual circumstance has taken place as a program runs Errors – events that signal the interpreter is having problems that may be unrelated to your program Consider the following code: import java.util.Scanner; public class EnterNumber { public static void main(String[ ] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a whole number between 0 and 9: "); int guess = input.nextInt(); System.out.println(" Your guess is " +guess); } } This program has a few flaws. What happens when any integer is entered? What happens when a decimal value is entered? When an integer outside the desired range is entered, the program continues with the invalid value When a decimal is entered, the program comes crashing to the ground The key to fixing a program bug is examining the message that appears when the program crashed Exception in thread "main" java.util.InputMismatchException The Java programming language has a mechanism called exception handling With exception handling, a program can detect that things are about to go wrong and respond by creating a brand new object That object is from the Exception class When handled properly, we can catch the exception, execute some recovery code and move on to the next statement ClassNotFoundException IOException Exception RunTimeException Many others ArithmeticException NullPointerException IndexOutOfBounds Exception IllegalArgument Exception Throwable LinkageError Error VirtualMachineError Many others Many others System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. LinkageError Error VirtualMachineError Many others Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. ClassNotFoundException IOException Exception RunTimeException Many others ArithmeticException NullPointerException IndexOutOfBounds Exception IllegalArgument Exception RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions. Unchecked exceptions reflect programming logic errors that are not recoverable NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array These are the logic errors that should be corrected in the program. To catch the problem before the program crashes, Java provides some assistance: throw – creates a new exception object throws – passes the exception from a method to the code try – encloses code that has a potential exception catch – deals with the exception, buries it, and then moves on To catch the problem before the program crashes, Java provides some assistance: throw – creates a new exception object throws – passes the exception from a method to the code try – encloses code that has a potential exception catch – deals with the exception, buries it, and then moves on try block Segment of code in which something might go wrong Attempts to execute Acknowledging exception might occur try block includes: Keyword try Opening and closing curly brace Executable statements Which might cause exception catch block Segment of code Immediately follows try block Handles exception thrown by try block preceding it Can “catch” Object of type Exception Or Exception child class throw statement Sends Exception out of method Can be handled elsewhere catch block includes: Keyword catch Opening and closing parentheses Exception type Name for Exception object Opening and closing curly braces Statements to handle error condition finally block Use for actions you must perform at end of try...catch sequence Use finally block to perform cleanup tasks Executes regardless of whether preceding try block identifies an Exception Let’s catch our decimal exception: import java.util.Scanner; public class EnterNumber { public static void main(String[ ] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a whole number between 0 and 9: "); try { int guess = input.nextInt(); System.out.println(" Your guess is " +guess); } catch (Exception e) { System.out.println("Not a valid guess"); } } } We can now catch the InputMismatch With the try statement, the program now terminates gracefully instead of crashing The trick is to enclose the scanner input statement inside a try clause Now the computer watches for exceptions If an exception is thrown, the computer jumps straight to the catch clause getMessage( ) Since an exception is an object, the getMessage method may provide additional information about the exception try { int guess = input.nextInt(); System.out.println(" Your guess is " +guess); } catch (Exception e) { System.out.println("Not a valid guess"); System.out.println("Message: " + e.getMessage( )); } printStackTrace( ) Use this method if you want to see the actual trace of the exception Similar to the crash message try { int guess = input.nextInt(); System.out.println(" Your guess is " +guess); } catch (Exception e) { System.out.println("Not a valid guess"); System.out.println("Message: " + e.getMessage( )); e.printStackTrace( ); } We caught a general Exception, but we can also catch specific exceptions which may need to be handled separately We can also have multiple catch statements with the try statement try { int guess = input.nextInt(); System.out.println(" Your guess is " +guess); } catch (java.util.InputMismatchException e) { System.out.println("Not a valid guess"); } Most ordinary exceptions that might be thrown within a method must be accounted for in one of two ways: 1. 2. The code that can throw an exception is placed within a try block, and the possible exception is caught in a catch block within the same method The possible exception can be declared at the start of the method definition by placing the exception class name in a throws clause Our code still has an issue with a valid integer input where our input value may be outside our desired range (number between 0 and 9) Let us use the IllegalArgumentException to handle our range issue We define the throw as part of the main import java.util.Scanner; public class EnterNumber { public static void main(String[ ] args) throws IllegalArgumentException{ Scanner input = new Scanner(System.in); System.out.print("Enter a whole number between 0 and 9: "); try { int guess = input.nextInt(); if (guess < 0 || guess > 9) throw new IllegalArgumentException(); } catch (java.util.InputMismatchException e) { System.out.println("Not a valid guess"); } catch (IllegalArgumentException e) { System.out.println("Not between 0 and 9"); } } } Before object-oriented programming languages Errors handled with confusing, error-prone methods When any method fails Program sets appropriate error code Difficult to follow Application’s purpose and intended outcome lost in maze of if statements Coding mistakes because of complicated nesting Java’s object-oriented, error-handling technique Statements of program that do “real” work Placed together where logic is easy to follow Unusual, exceptional events Grouped Moved out of the way Advantage to object-oriented exception handling Flexibility in handling of error situations Let’s write our code to prompt the user to guess again if an invalid input occurs We will use a while loop for the multiple inputs as needed Need to accept the input, then check for accuracy We can input as a string Then parse as an integer import java.util.Scanner; public class EnterNumber { public static void main(String[ ] args) throws IllegalArgumentException{ int guess = 0; boolean validGuess = false; Scanner input = new Scanner(System.in); while (!validGuess){ System.out.print("Enter a whole number between 0 and 9: "); String guessInput = input.next(); // continued on next slide try { guess = Integer.parseInt(guessInput); if (guess < 0 || guess > 9) throw new IllegalArgumentException(); else validGuess = true; } catch (NumberFormatException e) { System.out.println("Not a valid integer"); System.out.println("Try again"); } catch (IllegalArgumentException e) { System.out.println("Not between 0 and 9"); System.out.println("Try again"); } } System.out.println("Your guess is " + guess); } }