java programming n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Java Programming PowerPoint Presentation
Download Presentation
Java Programming

Loading in 2 Seconds...

play fullscreen
1 / 33

Java Programming - PowerPoint PPT Presentation


  • 62 Views
  • Uploaded on

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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Java Programming' - romney


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
java programming

Java Programming

Exception Handling

Chapter 12

exceptions
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
exceptions1
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);

}

}

exceptions2
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
exceptions3
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
exceptions4
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
exception types
Exception Types

ClassNotFoundException

ArithmeticException

IOException

Exception

NullPointerException

RunTimeException

IndexOutOfBounds

Exception

Many others

Throwable

IllegalArgument

Exception

LinkageError

Many others

Error

VirtualMachineError

Many others

system errors
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

exception
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

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

unchecked exceptions
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.
exceptions6
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
exceptions7
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
try statement
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
try statement1
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
try statement2
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
try statement3
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
exceptions8
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

exceptions9
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
exceptions10
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( ));

}

exceptions11
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( );

}

exceptions12
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");

}

the catch or declare rule
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
declare rule
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
delcare rule
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"); } }}

advantages
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
advantages3
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
final code
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
slide32

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

slide33

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

}

}