1 / 33

Java Programming

Java Programming. Exception Handling Chapter 12. Exceptions. 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

romney
Download Presentation

Java Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Programming Exception Handling Chapter 12

  2. Exceptions • 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

  3. Exceptions • 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); } }

  4. Exceptions • 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

  5. Exceptions • The key to fixing a program bug is examining the message that appears when the program crashed • Exception in thread "main" java.util.InputMismatchException

  6. Exceptions • 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

  7. Exception Types ClassNotFoundException ArithmeticException IOException Exception NullPointerException RunTimeException IndexOutOfBounds Exception Many others Throwable IllegalArgument Exception LinkageError Many others Error VirtualMachineError Many others

  8. System Errors • 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

  9. Exception • Exception describes errors caused by your program and external circumstances. • These errors can be caught and handled by your program. ClassNotFoundException ArithmeticException IOException Exception NullPointerException RunTimeException IndexOutOfBounds Exception Many others IllegalArgument Exception

  10. Exceptions RuntimeException, Error and their subclasses are known as uncheckedexceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.

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

  12. Exceptions • 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

  13. Exceptions • 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

  14. Try Statement • 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

  15. Try Statement • 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

  16. Try Statement • 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

  17. Try Statement • finallyblock • 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

  18. Try Statement

  19. Exceptions • 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

  20. Exceptions • 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

  21. Exceptions • 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( )); }

  22. Exceptions • 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( ); }

  23. Exceptions • 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"); }

  24. The Catch or Declare Rule • Most ordinary exceptions that might be thrown within a method must be accounted for in one of two ways: • 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

  25. Declare Rule • 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

  26. Delcare Rule 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"); } }}

  27. Advantages • 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

  28. Advantages

  29. Advantages

  30. Advantages • 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

  31. Final Code • 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

  32. import java.util.Scanner; public class EnterNumber { public static void main(String[ ] args) throws IllegalArgumentException{ int guess = 0; booleanvalidGuess = 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

  33. 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); } }

More Related