PROG-J - M03 - C02 - SLM - Exceptions and Exception Handling

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Chapter Table of Contents

Chapter 3.2

Exceptions and Exception Handling


Aim ..................................................................................................................................................... 155
Instructional Objectives................................................................................................................... 155
Learning Outcomes .......................................................................................................................... 155
3.2.1 Exception Handling Fundamentals ...................................................................................... 156
Self-assessment Questions ...................................................................................................... 159
3.2.2 Exception Types ...................................................................................................................... 160
(i) Checked Exceptions ........................................................................................................... 161
(ii) Error Exceptions................................................................................................................ 161
(iii) Run – time Error .............................................................................................................. 162
Self-assessment Questions ...................................................................................................... 162
3.2.3 Exception Handling Mechanism in Java .............................................................................. 163
Self-assessment Questions ...................................................................................................... 176
3.2.4 Java built-in Exceptions.......................................................................................................... 177
3.2.5 Creating Exception Subclasses .............................................................................................. 177
Self-assessment Questions ...................................................................................................... 179
Summary ........................................................................................................................................... 180
Terminal Questions.......................................................................................................................... 180
Answer Keys...................................................................................................................................... 181
Activity............................................................................................................................................... 182
Bibliography ...................................................................................................................................... 183
Video Links ....................................................................................................................................... 183
Aim
To provide students with the basics of exceptions and exception handling mechanisms

Instructional Objectives
After completing this chapter, you should be able to:

• Explain errors, its types and exception

• Demonstrate exception handling mechanism*

• Illustrate java built-in exceptions

• Explain the role of exceptions in java

• Illustrate exception subclasses

Learning Outcomes
At the end of this chapter, you are expected to:

• Differentiate between compile time errors and run-time errors

• Demonstrate exception hierarchy in java

• Differentiate checked and unchecked exceptions in java

• Identify Java built-in exceptions

• Apply catch to handle chained exceptions

• Mention the differences between final, finally and finalise keywords in java

155
3.2.1 Exception Handling Fundamentals
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That process may choose
to handle the exception itself, or pass it on. Each way, at some point, the exception is caught
and treated. The Java run-time system can generate exceptions, or your code can manually
generate them. Exceptions thrown by Java relate to fundamental errors that violate the rules of
the Java language or the constraints of the Java execution environment. Manually created
exceptions are typically used to notify some error condition to the caller of a method.

Usually, some problems will arise during execution of all programs irrespective of all
programming languages. In Java, these problems are termed as exceptions. The flow of the
program will get disrupted if an exception occurs or the program gets terminated abnormally
without recommending any solutions. Hence, these exceptions should be handled properly and
timely.

There are different reasons for exceptions to occur. Some of them are:

• If a user enters an indefensible data.

• Searching a file which is to be opened but not in its track (not found).

• Losing a network connection in the middle of communication or the pragmatic


machine run out of memory.

Java exception handling is accomplished via five keywords: try, catch, throw, throws and
finally. Briefly, here is how they work. Program statements that you want to monitor for
exceptions are received within a try block. If an exception occurs within the try block, it is
thrown. Your code can catch this exception (using catch) and handle it in some rational
manner. The Java run-time system automatically throws System-generated exceptions. To
manually throw an exception, just use the keyword throw. Any exception that is thrown out of
a method must be specified as such in a throws clause. Any code that absolutely must be
executed after a try block completes is put in a final block.

156
It is the general structure of an exception-handling block:

try
{
// block of code to observe for errors
}
catch (Exception1 ex)
{
// exception handler for Exception1
}
catch (Exception2 ex)
{
// exception handler for Exception2
}
// ...
finally
{
// block of code will be execute after try block ends
}

For example,

Consider a user wants to read some data from a file using ‘FileReader’ function. Say the
specified file and its constructor does not exist during read data from the file using ‘FileReader’.
Then, the class in this program will throw a FileNotFoundException and the Java compiler
prompts the user to handle the exception.

importjava.io.File;
importjava.io.FileReader;
public class FilenotFound_Demo
{
public static void main (String args [])
{
File f=new File ("P://newfile.txt");
FileReader km = new FileReader (f);
}
}

While compiling the above program, user will get an exception:

C:\>javac FilenotFound_Demo.java

FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be


caught or declared to be thrown: FileReader km =newFileReader(f);

157
Advantages of exception handling:

In Java, The core advantage of exception handling is to maintain the regular flow of the
application. An exception disrupts the normal circulation of the application that is why we use
exception handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;
statement 4; //exception occurs
statement 5;
statement 6;
statement 7;

Suppose there are 7 statements in your program and there occurs an exception at statement 4,
rest of the code will not be performed (or executed) i.e., statement 5 to 7 will not run. If we
implement exception handling, rest of the statement will be run or execute. That is why we use
exception handling in Java.

Difference between error and exception:

Errors Exceptions

Exceptions in java are of type


Errors in java are of type java.lang.Error.
java.lang.Exception.

Exceptions include both checked as well as


All errors in java are unchecked type.
unchecked type.

Checked exceptions are known to compiler


Errors happen at run time. They will not
whereas unchecked exceptions are not known
be known to compiler.
to compiler because they occur at run time.

You can recover from exceptions by handling


It is impossible to recover from errors.
them through try-catch blocks.

Errors are mostly caused by the


Exceptions are mainly caused by the
environment in which application is
application itself.
running.

158
For example, Checked Exceptions :
For example, SQLException, IOExceptionUnchecked
java.lang.StackOverflowError, Exceptions :
java.lang.OutOfMemoryError ArrayIndexOutOfBoundException,
ClassCastException,NullPointerException

Table 3.2.1: Difference between Errors and Exceptions

Self-assessment Questions
1) ___________keyword is used to monitor the exceptions.
a) try b) finally
c) throw d) catch

2) Identify which of the following keyword is NOT a part of exceptional handling.


a) finally b) thrown
c) catch d) try

3) When does exception in Java arise in code sequence.


a) Compilation time b) Can occur any time
c) Runtime d) None of these

159
3.2.2 Exception Types
All exception models are subclasses of the built-in class Throwable. Hence, Throwable is at the
peak of the exception class hierarchy. Immediately below Throwable are two subclasses that
partition exceptions into two well-defined branches. Exception heads one branch. This class is
used for exceptional conditions that user programs should catch. It is also the class that you
will subclass to develop your custom exception types. There is a momentous subclass of
Exception, called Runtime Exception. Exceptions of this kind are automatically defined for the
programs that you write and include things such as division by zero and invalid array indexing.

Figure 3.2.1: Exception Hierarchy

160
Difference between check and uncheck exceptions:

Checked Exception: The classes that extend Throwable class except Error and Runtime
Exception are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.

Unchecked Exception: The classes that extend Runtime Exception are associated as unchecked
exceptions. For example, Arithmetic Exception, NullPointer Exception, ArrayIndexOut
OfBoundsException etc. Unchecked exceptions are not checked at compile-time somewhat
they are checked at runtime.

There are three types of exceptions occur while exception handling. They are:

1. Checked
2. Error
3. Run-time

(i) Checked Exceptions


Checked exceptions are the one of the kinds of exceptions that either must be caught or
declared in the method in which it is thrown.

For example, Assume a user is using FileReader class to read a character file.

publicFileReader(String fileName)
throwsFileNotFoundException //FileReader constructor is invoked and the exception is
thrown//

(ii) Error Exceptions


The error is the second kind of exception. When this sort of exception occurs, JVM (Java
Virtual Machine) will create an exception object. These objects all derive from’ throwable class
where it has two main subclasses, the first one is Error and second one is Exception.

For example, when hardware fails, JVM might run out of resources but it is possible for an
application to catch the error and notify the user, saying the application will close down until
the underlying problem is dealt with.

161
(iii) Run – time Error
A program may contain so many errors like “an element of an array does not exist, logic error,
termination errors, etc.” They may cause because of human error or may be a programmatic
error like method called will return a null value, etc.

When a program executes with these errors an exception occurs which is termed as run time
exception.

The other section is topped by Mistake/Error, which describes exceptions that are not expected
to be caught under normal circumstances by your program. Exceptions of type Error are made
by the Java run-time system to indicate errors are having to do with the run-time situation,
itself. In Java, Stack Overflow is an example of such an error.

Self-assessment Questions
4) ____________ is a super class of all exceptional type classes.
a) String b) RuntimeException
c) Cachable d) Throwable

5) Identify which of the following class is related to all the exceptions that can be caught
using catch?
a) Error b) Exception
c) RuntimeException d) All the above

6) Which exception will be submitted, when JVM runs down of memory?


a) MemoryBoundException b) OutofRangeException
c) NullReferenceException d) OutofMemoryError

162
3.2.3 Exception Handling Mechanism in Java
Exception handling mechanism provides a clear way of checking errors without modifying the
code. Also used to identify the errors directly by providing signals (error statement) without
making any side effects to the methods or functions of the program.

Java exceptions are objects and they are primarily termed as checked exceptions. That is, the
compiler automatically verifies the method (declared by the programmer) and throws the
exception using the throwable function. There are many ways to handle the exceptions.

Some of them are as follows:

a) Using try and catch block

b) Multiple catch clauses

c) Nested try statements

d) The throw keyword

e) The throws keyword

f) The finally block

a) Using try and catch block:

To defend against and examine a run-time error, just enclose the code that you want to monitor
inside a try block. Immediately following the try block, include a catch clause that specifies the
exception type that you wish to capture. To explain how easily this can be done, the following
program includes a try block and a catch clause that processes the ArithmeticException
generated by the division-by-zero error:

class Except2
{
public static void main(String args[])
{
int p, q;
try
{ // monitor a block of code.
p = 0;
q = 42 / p;
System.out.println("It will not be printed.");
} catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}

163
System.out.println("After catch block statement.");
}
}

This program generates the following output: Division by zero.

After catch block statement.

• Note that the signal to "println( )" inside the try block is never executed. Once an
exception is thrown, program control transfers out of the try block into the catch block.
Put differently; the catch is not “called,” so execution never “returns” to the try block
from a catch block. Hence, the line “Is will not be printed.” is not displayed. Once the
catch statement has executed, program control continues with the next line in the
program following the entire try/catch process.

• A try and its catch block statement form a unit. The scope of the catch clause is
restricted to those declaration specified by the immediately preceding try statement. A
catch statement cannot catch an exception thrown by another try statement (except in
the case of nested try statements, described shortly). Curly braces must surround the
statements that are protected by try. (That is, they must be within a block.) You cannot
use try with a single declaration.

Here is the individual description of try and catch block for your better understanding:

Try Block:

The Try block is a cooperative block of catch. Without catch block, try block is illogical. A catch
block executes only if an exception of a particular type occurs within the try block. A try block
is always followed by a catch block.

Syntax:
try
{
……………. //statement;
…………….//statement;
}
Catch Block:

The catch block is associated with the try block. It handles the type of exception indicated by
its argument. Here, the argument type of exception inherits from the Throwable class.

164
Syntax:
try
{
Catch (ExceptionType name)
{
………….// error handling code
}
Catch (ExceptionType name) { }
}

The code of a catch block is executed only if and when the exception handler is invoked.

Sample Program:
packagecom.beingjavaguys.core;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;

public class ExcHanding


{
public static void main(String args[])
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter your good name : ");
try
{
String input = reader.readLine();
System.out.println("You wrote : "+input);// Exception prone area
} catch (IOException e)
{ try catch block
e.printStackTrace();
}
}
}
Output:
Enter your good name: Magnus

You wrote: Magnus

b) Multiple Catch clause:

Some cases in Multiple Catch clause, more than one exception could be raised by a single piece
of code. To handle this type of situation, you can specify two or more catch clauses, each
detecting a different kind of exception. When an exception is thrown, each catch statement is
inspected in order and the first one whose type matches that of the exception is executed. After

165
one catch statement compilation, another are bypassed and execution continues after the
try/catch block.

Syntax:
Catch (IOException)
{
//error statement;
throw;
catch (IOException)
{
//error statement;
throw;
}

The following example traps two different exception types:

// Demonstrate multiple catch statements.


class MultiCatch
{
public static void main(String args[])
{
try
{
int i = args.length;
System.out.println("i = " + i);
int j = 42 / i;
int a[] = { 1 };
a[42] = 99;
} catch(ArithmeticException e)
{
System.out.println("Divide by zero: " + e);
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try or catch blocks.");
}
}

This program will produce a division-by-zero exception if it is started with no command line
arguments, since a will equal zero. It will survive the division if you provide a command-line
argument, setting a to something larger than zero. But it will cause an
"ArrayIndexOutOfBoundsException" since the int array a has a length of 1, yet the program
attempts to assign a value to a[42].

166
Generated output by running it both ways:

C:\>java MultiCatch
i=0
Divide by zero: java.lang.ArithmeticException: / by zero
After try or catch blocks.
C:\>java MultiCatch TestArg
i=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try or catch blocks.

When you use multiple catch statements in multiple catch clause, it is necessary to remember
that exception subclasses must come before any of theirs super classes. It is because a catch
statement that uses a superclass will catch exceptions of that type of its subclasses. Therefore, a
subclass would never be moved if it came after its superclass. Moreover, in Java, unreachable
code is an error. For example, consider the following program:

/* this program contains an error.

A subclass necessity come before its superclass in a series of catch statements. If not, the
unreachable code will be created and a compile-time error will result.
*/
class SuperCatch
{
public static void main(String args[])
{
try
{
int i = 0;
int j = 42 / i;
} catch(Exception e)
{
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e)
{ // ERROR - unreachable
System.out.println("This is never reached.");
}
}
}

167
If you try to compile this program, you will receive an error message stating that the second
catch statement is unreachable because the exception has already been caught. Since
ArithmeticException is a subclass of Exception, the first catch statement will handle all

Exception-based errors, including ArithmeticException. It means that the second catch


statement will never be executed. Before the fix, the problem, reverse the order of the catch
statements.

c) Nested try statement:

The try statement can be nested statement. It means a try statement can be inside the block of
another try. Each time a try statement is entered, the context of that exception is pushed on the
stack. If an inner/personal try statement does not have a catch handler for a particular
exception, the stack is unwound and the next try statement’s catch handlers are inspected for a
match. It extends until one of the catch statements succeeds, or until all of the nested try
statements are exhausted. If no catch statement matches, then the Java run-time system will
handle the exception.

Nested try statement comprises of a try block within another try block. It is used in some
situation where a part of a block may cause one error and the entire clock itself may cause
another error.

Syntax:
try
{
statement a;
statement b;
try
{
statement a;
statement b;
}
}
Catch (Exception e)
{}
Catch (Exception e)
{}

Let's take an example that uses nested try statements:

class NestTry
{
public static void main(String args[])
{

168
try
{
int i = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int j = 34 / i;
System.out.println("i = " + i);
try
{ // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(i==1) i = i/(i-i); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(i==2)
{
int a[] = { 1 };
a[34] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e)
{
System.out.println("Divide by zero: " + e);
}
}
}

As you can see, this program nested try statement comprises of a try block within another try
block. The program works as follows. When the program is executed with no command-line
arguments, a divide-by-zero exception is created by the outer try block. Execution of the
program with one command-line argument generates a divide-by-zero exception from within
the nested try block. Since the inside block does not catch this exception block, it is passed on
to the outer try block, where it is handled. If you execute the program with two command-line
arguments, an array boundary exception is generated from within the inside try block. Here
are sample runs that illustrate each case:

C:\>javac NestTry

Divided by zero:java.lang.ArithmeticException :/ By zero

C:\>javac NestTry One

i=1

169
Divided by zero:java.lang.ArithmeticException :/ By zero

C:\>javac NestTry Two

i=2

Array index out-of-bounds:

java.lang.ArrayIndexOutOfBoundExceptions :34

Another Example for Nested try block:

class Nested
{
public static void main(String args[])
{
try
{
try
{
System.out.println("I am going to divide");
int b =33/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[7];
a[7]=6;
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("another statement");
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("Simple flow..");
}
}

170
Output:
I am going to divide

Java.lang.ArithmaticException :/by zero

Java.lang.ArrayIndexOutOf Bound Exception :7

another statement

Simple flow..");

d) Throw keyword

Throw The keyword is used to declare an exception. It is used to give information to the
programmer that exception may occur so it will be finer to provide an exceptional handling
code so that the flow of the program does not get affected.

Example demonstrating throw keyword:

class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}
public static void main(String args[])
{
avg();
}
}

In the preceding example, the avg( ) method throw an instance of ArithmeticException, which
is successfully handled using the catch statement.

Syntax:
type method_name(parameter_list) throws exception_list
{
//definition of method
}

171
Throw new throwable’s subclass:

Let's take a sample program that creates and throws an exception. The handler that catches the
exception rethrows it to the outer handler.

// Demonstrate throw.
class ThrowDemoEx
{
static void demoproc()
{
try
{
throw new NullPointerException("demo");
} catch(NullPointerException e)
{
System.out.println("Caught inside demoproc.");
throw e; // re throw the exception
}
}
public static void main(String args[])
{
try
{
demoproc();
} catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}

The above program gets double chances to deal with the similar error. First, main( ) sets up an
exception context and then calls demoproc( ). The demoproc( ) method then sets up another
exceptionhandling context and immediately throws a new instance of NullPointerException,
which is caught on the next line. The exception is then rethrown.

Here is the resulting output:

Caught inside demoproc.

Recaught: java.lang.NullPointerException: demo

e) Throw keyword :

Any method able of causing exceptions must list all the exceptions possible during its
execution, so that anybody calling that method gets an ancient knowledge about which
exceptions to handle. A method can do so by using the throws keyword.

172
Syntax:
type method_name(parameter_list) throws exception_list
{
//definition of method
}

Example demonstrating throws keyword:

class Test
{static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
public static void main(String args[])
{
try
{
check();
}catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}

Note: It is essential for all exceptions, except the exceptions of type Error and
RuntimeException, or any of their subclass.

f) The finally block:

The final block is used to handle an unexpected exception in a program. It always executes
when the try block exits. It uses the break statement to avoid programmers to use the cleanup
code in the program. But it is advisable to use clean up code even when no exceptions are
anticipated. The final keyword is designed to address this contingency.

The "finally" keyword generates a block of code that will be done after a try or catch block has
completed and before the code following the try or catch block. The final block will execute
either or not an exception is thrown. If an exception is thrown, the final block will perform
even if no catch statement matches the exception.

At any time, a method is about to return to the caller from inside a try or catch block, via an
uncaught exception or an explicit return statement, the final clause is also executed just earlier
the method returns. It can be useful for closing file handles and free up any other resources that

173
might have been allocated at the beginning of a process with the purpose of ordering of them
before returning. The final clause is arbitrary. But, each try statement requires at least one catch
or a final clause.

Here is an example program that shows three methods that exist in various ways, none without
executing their finally clauses:

// demonstrate finally.
class FinallyTest
{
// through an exception out of the method.
static void procX()
{
try
{
System.out.println("inside procX");
throw new RuntimeException("demo");
}
finally
{
System.out.println("procX's finally");
}
}
// Return from within a try block.
static void procY()
{
try
{
System.out.println("inside procY");
return;
} finally
{
System.out.println("procY's finally");
}
}
// Execute a try block normally.
static void procZ()
{
try
{
System.out.println("inside procZ");
} finally
{
System.out.println("procZ's finally");
}
}
public static void main(String args[])
{
try

174
{
procX();
} catch (Exception e)
{
System.out.println("Exception caught");
}
procY();
procZ();
}
}

In this above example, procX( ) prematurely breaks out of the try by throwing an exception.
The "finally" clause is executed on the way out. procY( )’s try statement is exited via a return
statement. The "finally" clause is executed before procY( ) returns. In procZ( ), the try statement
usually runs, without error. However, the "finally" block is still executed.

Output generated by the preceding Program:

inside procX

procX’s finally

Exception caught

inside procY

procY’s finally

inside procZ

procZ’s finally

175
Self-assessment Questions
7) Which of the following clause will be done even if no exceptions are found?
a) Finally b) Nested catch
c) Throw d) Catch

8) Try block is associated with _________ block.


a) Finally b) Catch
c) Finally & catch d) None of the above

9) Identify which of the following keyword must be used to handle the exception thrown
by try block?
a) Try b) Finally
c) Throw d) Catch

176
3.2.4 Java built-in Exceptions
Java platform provides several exception classes under a package java.lang. The most general
form of exception is the Runtime exception. List of Java built-in exceptions are given below:

Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
Assignment to an array element of an incompatible
ArrayStoreException
type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on an
IllegalMonitorStateException
unlocked thread.
IllegalStateException Environment or application is in incorrect state.
Requested operation not compatible with current
IllegalThreadStateException
thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.

Table 3.2.2: Java Built-in Exception and its Description

3.2.5 Creating Exception Subclasses


In Java, the user can create their exception subclass by simply extending Java option java class.
There are some steps to be followed to create exception subclasses. They are:

Step 1: Define a constructor in the program where an exception subclass is to be created.

Step 2: Another way of creating an exception subclass is that an user can override the
tostring( ) function to display your customised message on the catch.

177
By default, no methods are defined by exceptions. Instead they are defined by the method
Throwable available to them. Some of them are shown below:

ThrowablegetCause( ) – returns the exception that underlies the current exception

String getLocalisedMessage( ) – returns a localised description

String getMessage( ) – returns a description of the exception

Example program to create a customise exception type:

classMyExceptionextends Exception
{
privateint detail;
MyException(int p)
{
detail = p;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
publicclass Main
{
staticvoid compute(int a) throwsMyException
{
System.out.println("Called compute(" + p + ")");
if (p > 10)
thrownewMyException(a);
System.out.println("Simple exit");
}
publicstaticvoid main(String args[])
{
try
{
compute(2);
compute(21);
} catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}
Output:

Simple Exit

178
Creating exception subclass can be classified in two types. They are:

1. Chained exceptions

2. Using exceptions

1. Chained Exceptions:

Exception throwing another exception is called as chained exceptions. The first exception is the
cause of the second one and it is very useful to know when it occurs.

Methods and constructors in throwable that supports chained exceptions are as follows:

• ThrowablegetCause( )

• ThrowableinitCause (Throwable)

• Throwbale (String, Throwbale)

• Throwable (Throwable)

The following example shows how to use a chained exception:

try
{} catch (IOException e)
{
throw new SampleException("Other IOException", e);
}

In the above example program, new SampleException is created with the original IOException
and the chain exception is thrown up.

2. Using Exceptions:

An exception subclass can be used as the parent class of another exception called as linked
exceptions. These exceptions are inappropriate because they are either too differentiate
(specified for special function) or completely unrelated to another exception.

Self-assessment Question
10) _________ Package contain all Java built in exceptions?
a) Java.io b) Java.util
c) Java.lang d) Java.net

179
Summary
o In Java, errors are termed as exceptions.

o Checked exceptions are declared in the method in which it is thrown.

o Try block is associated with a catch block.

o Java exceptions are objects and they are primarily termed as checked exceptions.

o The final block is used to handle an unexpected exception in a program.

Terminal Questions
1. Differentiate checked and unchecked exceptions in java.

2. What are Java built-in exceptions and explain its types?

3. Mention the differences between final, finally and finalise keywords in java.

180
Answer Keys
Self-assessment Questions
Question No. Answer

1 a
2 b
3 c
4 d
5 b
6 d
7 a
8 b
9 d
10 c

181
Activity
Activity Type: Online

Description:

A method named average( ) has one argument that is an array of strings .it converts these
to double values and returns their average. The method generates a NullPointerException
if an array element is null. Write a program that illustrates how to declare and use this
method. Include a throws clause in the method declaration to indicate that these problems
can occur.

182
Bibliography

Video Links
Topic Link

http://www.tutorialspoint.com/java/java_exceptions.ht
Java Exceptions
m

http://java.about.com/od/Handling-
Exception Handling
Exceptions/a/Types-Of-Exceptions.htm
http://www.c-
Errors and exceptions sharpcorner.com/UploadFile/fd0172/difference-
between-an-error-and-exception

183
Notes:

184

You might also like