You are on page 1of 15

Exceptions in Java

When Good Programs Go Bad


8A variety of errors can occur when a
program is running. For example:
– user input error. bad url
– device errors. remote server unavailable
– physical limitations. full disk
– code errors.
8when an error occurs
– return to safe state, save work, exit gracefully
8error handling code may be far removed
from code that caused the error
How to Handle Errors?

8It is possible to detect and handle errors of


various types.
Exceptions
8Many languages, including Java use a
mechanism know as Exceptions to handle
errors at runtime
– In Java Exception is a class with many
descendants.
– ArrayIndexOutOfBoundsException
– NullPointerException
– FileNotFoundException
– ArithmeticException
– IllegalArgumentException
Creating Exceptions
8As a program runs, if a situation occurs that
is handled by exceptions then an Exception
is thrown.
– An Exception object of the proper type is created
– flow of control is transferred from the current
block of code to code that can handle or deal
with the exception
– the normal flow of the program stops and error
handling code takes over (if it exists.)
Runtime Errors
1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.

Run

Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
6
Catch Runtime Errors
1 import java.util.*; Run
2
3 public class HandleExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 boolean continueInput = true;
7
8 do {
9 try {
10 System.out.print("Enter an integer: ");
11 int number = scanner.nextInt();
12 If an exception occurs on this line,
13 the rest of lines in the try block are // Display the result
14 skipped and the control is System.out.println(
15 transferred to the catch block. "The number entered is " + number);
16
17 continueInput = false;
18 }
19 catch (InputMismatchException ex) {
20 System.out.println("Try again. (" +
21 "Incorrect input: an integer is required)");
22 scanner.nextLine(); // discard input
23 }
24 } while (continueInput);
25 }
13 }
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
Exception handling

– Catch errors before they occur


– Used when system can recover from error
• Exception handler - recovery procedure
• Error dealt with in different place than where it
occurred
– Useful when program cannot recover but
must shut down cleanly
The Basics of Java Exception Handling

8Exception handling
– Method detects error which it cannot deal
with
• Throws an exception
– Exception handler
• Code to catch exception and handle it
– Exception only caught if handler exists
• If exception not caught, block terminates
The Basics of Java Exception Handling
8 Format
– Enclose code that may have an error in try block
– Follow with one or more catch blocks
• Each catch block has an exception handler
– If exception occurs and matches parameter in catch block
• Code in catch block executed
– If no exception thrown
• Exception handling code skipped
• Control resumes after catch blocks

try{
code that may throw exceptions
}
catch (ExceptionType ref) {
exception handling code
}
Using try-catch Blocks
8If you want to handle a checked exception
locally then use the keywords try and
catch
8the code that could cause an exception is
placed in a block of code preceded by the
keyword try
8the code that will handle the exception if it
occurs is placed in a block of code preceded
by the keyword catch
Sample try and catch Blocks
public int countChars(String fileName)
{ int total = 0;
try
{ FileReader r = new FileReader(fileName);
while( r.ready() )
{ r.read();
total++;
}
r.close();
}
catch(FileNotFoundException e)
{ System.out.println("File named "
+ fileName + "not found. " + e);
total = -1;
}
catch(IOException e)
{ System.out.println("IOException occured " +
"while counting chars. " + e);
total = -1;
}
return total;
}
Mechanics of try and catch
8Code that could cause the checked
exception is placed in a try block
– note how the statements are included in one try block.
– Each statement could be in a separate try block with an
associated catch block, but that is very unwieldy (see
next slide)
8Each try block must have 1 or more
associated catch blocks
– code here to handle the error. In this case we just print
out the error and set result to -1
More try catch Mechanics
8If you decide to handle the possible
exception locally in a method with the try
block you must have a corresponding catch
block
8the catch blocks have a parameter list of 1
8the parameter must be Exception or a
descendant of Exception
8Use multiple catch blocks with one try
block in case of multiple types of
Exceptions
What Happens When
Exceptions Occur
8If an exception is thrown then the normal flow of
control of a program halts
8Instead of executing the regular statements the
Java Runtime System starts to search for a
matching catch block
8The first matching catch block based on data type
is executed
8When the catch block code is completed the
program does not "go back" to where the exception
occurred.
– It finds the next regular statement after the catch block

You might also like