Download Try and Catch

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
Try and Catch
Most of the errors that you have encountered have been compiler errors. Compilers
errors are typically syntax errors that are due to mistakes in the structure of the source
code. This could be due to misspelling, incorrect punctuation, or other mistakes in the
formal structure of the Java language statements.
The other types of errors that you could encounter are runtime errors. Another name
for a runtime error is exception. Exceptions are different than compiler errors.
Compiler errors are uncovered during the compilation process. A runtime error or
exception occurs while you are running your program. This means it had no compiler
errors and bytecode was generated by compiling.
Java has the ability to attempt a block of code and run another block of code if it
encounters a runtime error. This provides the ability to write error handlers that could
make your code more robust. To do this you use the try and catch blocks.
A try block is a block of code that you are trying to execute. If inside that block of
code it encounters an exception (runtime error) that you are looking for you will
execute the catch block. Assuming the catch block was written to catch that type of
exception. Remember that a block of code is zero or more statements enclosed within a
set of curly braces {}.
The catch block will be typed immediately following the try block that it written for.
Before we look at a try / catch example, we should review an actual runtime error. If
you prompt and accept for an int value and the user enters a String, your program will
crash.
System.out.println("Enter an integer number");
num = kb.nextInt();
You will get an exception that is a:
Exception in thread "main" java.util.InputMismatchException
You may have accidently gotten this before on earlier programming assignments. You
would have gotten the same exception had you been expecting an int value but the
user typed in a double value.
In some cases, you may use a try and catch block to attempt to make your program
more robust, and either recover from a runtime error, or at least display some message
to help make it clear what error had occurred.
Look at the code snippet below:
System.out.println("Enter an integer number");
try {
num = kb.nextInt();
}
catch (InputMismatchException e) {
System.out.println("You input the wrong kind of value," +
" I asked for an integer.");
}
The snippet above has a try block around the nextInt() method. Because there is a
chance for a exception (runtime error) in that line. The user could enter the wrong kind
of value.
Since the type of exception that we anticipate we could get is a
InputMismatchException, that is the type of exception we look for in the catch block.
The e, in the catch block is just the name of the parameter for the exception, you could
call it anything (any valid variable name).
You could even use that variable in your catch block if you like:
System.out.println("Enter an integer number");
try {
num = kb.nextInt();
}
catch (InputMismatchException e) {
System.out.println("You have a " + e);
System.out.println("\nThis means that you input the wrong" +
" kind of value, I asked for an" +
" integer.");
}
The above code will print the exception e, along with a friendlier explanation of the
error.
After the catch block has executed, the program will continue to execute your program
from that point. So, it may be that your program will still crash, but you at least printed
a good explanation of why it crashed.
Sometimes you can trap the error and keep running without crashing. Sometimes you
will even intentionally ask the user to do something that would crash your program, but
you plan on catching it. For example:
import java.util.*;
public class Average {
public static void main (String [] args) {
double average;
int x, num, sum, count;
Scanner kb = new Scanner(System.in);
sum = 0;
count = 0;
num = 0;
System.out.println("Enter the numbers to average");
System.out.println("Enter Done, when finished");
try {
num = kb.nextInt();
while (true) {
// loop forever
sum = sum + num;
count++;
num = kb.nextInt();
}
}
catch (InputMismatchException e) {
average = (double) sum / count;
}
if (count > 0)
System.out.println ("The average is " + average);
else
System.out.println ("You entered no values, so there"
+ " is no average");
}
}
You might have picked up on a change in the import statement. I used:
import java.util.*;
instead of:
import java.util.Scanner;
The * denotes a wild card which means it will bring in the part of the library that deals
with Scanners, as well as other parts of the java utilities which I needed for the
InputMismatchException. This means it will import all of java.util.
Basically, since I planned on catching the InputMismatchException I had to import the
right library files to make InputMismatchException recognizable. This is the same as if
you plan on using a Scanner, you have to import the right library files to make your
program recognize a Scanner.