0% found this document useful (0 votes)
77 views

Chapter Five - Exception Handling

The document discusses exception handling in Java. It defines exceptions as runtime errors that occur during program execution. There are three main types of exceptions: errors, checked exceptions, and runtime exceptions. The try-catch statement is used to handle exceptions by catching them in a catch block and providing exception handling code. Multiple catch blocks can be used to handle different specific exception types. Finally blocks are used for cleanup code that always executes whether an exception occurred or not.

Uploaded by

Kene Birhanu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Chapter Five - Exception Handling

The document discusses exception handling in Java. It defines exceptions as runtime errors that occur during program execution. There are three main types of exceptions: errors, checked exceptions, and runtime exceptions. The try-catch statement is used to handle exceptions by catching them in a catch block and providing exception handling code. Multiple catch blocks can be used to handle different specific exception types. Finally blocks are used for cleanup code that always executes whether an exception occurred or not.

Uploaded by

Kene Birhanu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

CHAPTER FIVE

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.

1 Exception Handling Overview


An exception is an indication of a problem that occurs during a program’s execution. An
exception is a runtime error. The name “exception” implies that the problem occurs infrequently — if
the “rule” is that a statement normally executes correctly, and then the “exception to the rule” is that a
problem occurs. When an exception occurs, the normal execution flow of the program will be
interrupted. Exception handling enables you to create applications that can resolve (or handle)
exceptions. In many cases, handling an exception allows a program to continue executing as if no
problem had been encountered. A more severe problem could prevent a program from continuing
normal execution, instead requiring it to notify the user of the problem before terminating in a
controlled manner.
Exceptions occur for various reasons. The user may enter an invalid input, for example, or the
program may attempt to open a file that doesn't exist, or the network connection may hang up, or the
program may attempt to access an out-of-bounds array element.
Here is an example. The program shown below terminates abnormally if you enter a floating-
point value instead of an integer.
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 :");
int num = reader.nextInt();
System.out.println("The number is :" + num);
}
}
The ouput of the program is:
Enter a number: 12.5
If 12.5 is entered for the integer variable, the program will terminate unexpectedly by
generating the exception shown below:

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

2 Exceptions and Exception Types


A Java exception is an instance of a class derived from Throwable. The Throwable class is
contained in the java.lang package, and subclasses of Throwable are contained in various
packages.

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.

Figure 1: The Throwable class hierarchy

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.

Related to input/output operations, such as invalid input,


reading past the end of a file, and opening a nonexistent file.
IOException Examples of subclasses of IOException are
InterruptedIOException, EOFException (EOF is short
for End Of File), and FileNotFoundException.

AWTException Exceptions in GUI components.

Runtime exceptions are represented in the RuntimeException class, which describes


programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
Runtime exceptions are generally thrown by the JVM. Examples of subclasses are shown below.

Dividing an integer by zero. Note that floating-point


ArithmeticException
arithmetic does not throw exceptions.

NullPointerException Attempt to access an object through a null reference variable.

IndexOutOfBoundsException Index to an array is out of range.

IllegalArgumentException A method is passed an argument that is illegal or


inappropriate.

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 {

public static void main(String[] args) {


int num[] = new int[4];
try{
System.out.println("Before exception is generated");
num[7]=10;
System.out.println("This will not be displayed");
}
catch(ArrayIndexOutOfBoundsException ex){
//catch the exception
System.out.println("Index-out-of bounds!");
}
System.out.println("After catch statement");
}
}
Output of the above program:
Before exception is generated
Index-out-of bounds!
After catch statement
The code you want to monitor for errors is contained within a try block. When an exception
occurs, the exception is thrown out of the try block and caught by the catch statement. Control passes to
the catch block, and the try block is terminated.
If no exception is thrown by a try block, no catch statements will be executed and program
control resumes after the catch statement.
Consider the following example :

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

4 Using Multiple catch Statements


The following example demonstrates the use of multiple catch statements:
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");
}
catch(ArrayIndexOutOfBoundsException ex){
//catch the exception
System.out.println("No Matching element found");
}
}
}
}
The output of the above program is as follows:
4/2 is 2
Cannot divide by zero
16/4 is 4
32/4 is 8
Cannot divide by zero
128/8 is 16
No Matching element found
No Matching element found

Page 6 of 6

You might also like