Download Exception Handling

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Exception Handling
The Java programming language uses exceptions to handle errors and other exceptional events.
What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of
instructions. When an error occurs within a method, the method creates an exception object and hands it off
to the runtime system. The exception object contains information about the error, including its type and the
state of the program when the error occurred.
//Attempt to read past the end of the array
public class BadArray
{ public static void main(String[] args)
1
{
2
int[] numbers = { 1, 2, 3 };
3
for (int i = 0; i <= 3; i++)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at BadArray.main(BadArray.java:7)
System.out.println(numbers[i]);
}
}
//Entering a non-integer value will result in an exception
import java.util.Scanner;
public class ParseIntError
{
public static void main(String[] args)
{ Scanner keyboard = new Scanner (System.in);
int number;
System.out.print("Enter your grade: "); Enter your grade: A
Exception in thread "main" java.lang.NumberFormatException: For input string: "A"
String str = keyboard.nextLine();
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
number = Integer.parseInt(str);
at java.lang.Integer.parseInt(Integer.java:447)
}
at java.lang.Integer.parseInt(Integer.java:497)
at ParseIntError.main(ParseIntError.java:10)
}}
How To Handle Exceptions In Your Program
It is the programmer’s responsibility to write code that detects and handles exceptions. Unhandled
exceptions will crash a program. You should create exception handlers, a section of code that gracefully
responds to exceptions.
To handle an exception, you use a try block followed by a catch block. The catch clause must specify the
type of Exception the catch block will handle.
try
{
// One or more statements that are executed, and can potentially throw an exception.
// The application will halt if the try block throws an exception
}
catch (ExceptionType ParameterName)
{
//This code is executed if the try block throws a specific Exception.
}
//The code will resume executing here whether or not an Exception occured
More about Exceptions
Exception objects are created from classes in the Java API hierarchy of exception classes. All of the
exception classes in the hierarchy are derived from the Throwable class.
Figure 1. There are over 360 different Exceptions. Here are a few.
The code in the try block may be capable of throwing more than one type of Exception. A catch clause
needs to be written for each type of Exception that could potentially be thrown. The JVM will run the first
compatible catch clause found. The catch clauses must be listed from most specific to most general.
// This program demonstrates how multiple exceptions can be caught with one try statement.
try
{
File file = new File(“SalesData.txt”);
//Open the file
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{ oneMonth = inputFile.nextDouble(); //Get a month’s sales amount
totalSales += oneMonth;
//Accumulate the month
months++;
//Increment the month
}
inputFile.close(); //Close File
System.out.println(“Average Sales:”+totalSales/months);
}
catch(FileNotFoundException e)
{ // Thrown by the Scanner constructor when the file is not found.
System.out.println( "The file " + filename + " does not exist.");
}
catch(InputMismatchException e)
{ // Thrown by the Scanner class's nextDouble method when a non-numeric value is found.
System.out.println( "Non-numeric data found in the file.”);
}
Exercise:
A date string should be formatted as 1-1-2009. Write a code segment that asks user to enter a
date and will determine if the date is valid string or not. If it is a correct date it will display
the month name written out (January 1, 2009).
A month should have a value between 1 and 12 and a day between 0 and 31.
Test your code with the following:
1-2009
//Invalid date
13-1-2009
//Invalid Month
Jan-1-2009
//Invalid Month
1 Jan 2009
//No Dashes Entered
1-44-2009
//Invalid day