Chapter Five - Exception Handling
Chapter Five - Exception Handling
EXCEPTION HANDLING
Objectives
After studying this lesson you should be able to:
• Explain basic concepts of Exception Handling in Java.
• Explain various Exceptions and Exception Types.
• Describe the Throwable class hierarchy.
• Explain the use of try-catch statements in Exception handiling.
• Describe usage multiple catch statements.
Page 1 of 6
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at ExceptionDemo.main(ExceptionDemo.java:18)
Note that several lines of information are displayed above in response to the invalid input. This
information, known as the stack trace, includes the name of the exception
(java.util.InputMismatchException) followed by the method call stack at the time the exception
occurred. The stack trace helps in debugging a program. Starting from the last line of the stack trace,
you see that the exception was detected in line 18 of the main method.
Each line of the stack trace contains the class name and method ( ExceptionDemo.main) along
with the file name and line number ( ExceptionDemo.java:18). Moving up the stack trace, you see
that the exception occurred in line 2050 in the nextInt method of the Scanner class, the exception
occurred in line 2091 in the overloaded nextInt method of the Scanner class, the exception occurred
in line 1461 in the next method of the Scanner class, the exception occurred in line 840 in the
throwFor method of the Scanner class. The last method in the call chain actually threw an
InputMismatchException.
But the following program reports an error message if 12.5 is entered for the integer variable
and the program continues normally executing after displaying the error message.
import java.util.Scanner;
import java.util.*;
public class ExceptionDemo {
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number :");
try {
int num= reader.nextInt();
System.out.println("The number is :" + num);
}
catch (InputMismatchException e)
{
System.out.println("There is type miss match :");
}
finally
{
System.out.println("This part is always done");
}
}
}
Page 2 of 6
Errors related to GUI components are included in the java.awt package; numeric exceptions
are included in the java.lang package because they are related to the java.lang.Number class.
You can create your own exception classes by extending Throwable or a subclass of
Throwable. Figure below shows some of Java's predefined exception classes.
The exception classes can be classified into three major types: Errors, Exceptions, and
Runtime Exceptions.
Errors are thrown by the JVM and represented in the Error class. Errors are not caused due to
user program. 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.
Errors that result from program activity are represented by sublcasses of Exception. Exceptions
are represented in the Exception class, which describes errors caused by your program and by
external circumstances. These errors can be caught and handled by your program. Examples of
subclasses of Exception.
ClassNotFoundException Attempt to use a class that does not exist. This exception
would occur, for example, if you tried to run a nonexistent
class using the java command, or if your program was
composed of, say, three class files, only two of which could be
Page 3 of 6
found.
RuntimeException, Error, and their subclasses are known as unchecked exceptions. All
other exceptions are known as checked exceptions, meaning that the compiler forces the programmer
to check and deal with them.
In most cases, unchecked exceptions reflect programming logic errors that are not recoverable.
For example, a NullPointerException is thrown if you access an object through a reference
variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access
an element in an array outside the bounds of the array. These are logic errors that should be corrected
in the program.
Unchecked exceptions can occur anywhere in a program. To avoid cumbersome overuse of try-
catch blocks, Java does not mandate that you write code to catch or declare unchecked exceptions.
Java exception handling is managed via 5 keywords: try, catch, throw, throws and
finally. Program statements that you want to monitor for exceptions are contained within a try-
block.
If an exception occurs within a try-block, it is thrown. Your code can catch this exception
using catch and handle it. System-generated exceptions are automatically thrown by java run-time
system. To manually throw an exception, use the keyword throw.
Page 4 of 6
3 Using try – catch statements for exception handling
General form of try – catch statement is:
try{
//block of code to monitor for errors
}
catch(ExceptionType1 exOb ) {
//handler for ExceptionType1
}
catch(ExceptionType2 exOb ) {
//handler for ExceptionType2
}
ExceptionType is the type of exception that has occurred. When an exception is thrown, it is
caught by its corresponding catch statement, which then processes the exception.
If no exception is thrown, then a try block ends normally, and all of its catch statements are
bypassed. Executions resumes with the first statement following the last catch. Catch statements are
executed only if an exception is thrown.
Example:
public class ExcDemo {
Page 5 of 6
public class ExcDemo {
public static void main(String[] args) {
int numer[] = { 4, 8, 16, 32, 64, 128 };
int denom[] = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.length; i++){
try{
System.out.println( numer[i] + "/" + denom[i]
+ " is " + numer[i]/denom[i]);
}
catch(ArithmeticException ex){
//catch the exception
System.out.println("Can not divide by zero");
}
}
}
}
Page 6 of 6