You are on page 1of 25

Exception Handling

Pre-assessment Questions
1. Which type of inheritance supports repeating inheritance?
a. Single level inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Multipath inheritance

2. Which keyword is used to define the constants in an interface?


a. super
b. public
c. private
d. final

NIIT Programming in Java Lesson 1B / Slide 1 of 25


Exception Handling

Pre-assessment Questions (Contd.)


3. Which concept of object-oriented programming is used in method overriding?
a. Polymorphism
b. Abstraction
c. Encapsulation
d. Inheritance

4. What is the return type of the methods declared in an interface?


a. Default
b. private
c. protected
d. public

NIIT Programming in Java Lesson 1B / Slide 2 of 25


Exception Handling

Pre-assessment Questions (Contd.)


5. Which type of inheritance enables you to inherit class data members and
methods from more than one superclass?
a. Single level inheritance
b. Multiple inheritance
c. Multilevel inheritance
d. Multipath inheritance

NIIT Programming in Java Lesson 1B / Slide 3 of 25


Exception Handling

Solutions to Pre-assessment
Questions
1. b. Multiple inheritance
2. d. final
3. a. Polymorphism
4. d. public
5. b. Multiple inheritance

NIIT Programming in Java Lesson 1B / Slide 4 of 25


Exception Handling

Objectives
In this lesson, you will learn to:
Identify the various types of exceptions in Java
Handle exceptions by using the try, catch, and finally clauses
Use the throw statement
Implement user-defined exceptions
Use assertions in Java

NIIT Programming in Java Lesson 1B / Slide 5 of 25


Exception Handling

Exceptions in Java
An exception can be defined as an abnormal event that occurs during program
execution and disrupts the normal flow of instructions.
Errors in a Java program are categorized into two groups:
Compile-time errors
Run Time errors
Concept of Exceptions:
The unexpected situations that occur during program execution are:
Running out of memory
Resource allocation errors
Inability to find files
Problems in network connectivity

NIIT Programming in Java Lesson 1B / Slide 6 of 25


Exception Handling

Exceptions in Java (Contd.)


Exception Classes

The following figure shows the Exception class heirarchy:

NIIT Programming in Java Lesson 1B / Slide 7 of 25


Exception Handling

Exceptions in Java (Contd.)

NIIT Programming in Java Lesson 1B / Slide 8 of 25


Exception Handling

Exceptions in Java (Contd.)


Built-in Exceptions
Java consists of the following categories of built-in exceptions:
Checked Exceptions
Unchecked Exceptions

NIIT Programming in Java Lesson 1B / Slide 9 of 25


Exception Handling

Exceptions in Java (Contd.)


The following table lists the various checked exceptions in Java:

Exception Cause of Creation

ClassNotFoundException Occurs when the Java run time system


is unable to find the class referred.

IllegalAccessException Occurs when you want to refer a class


that is not accessible.
InstantiationException Occurs when you try to create an
object of an abstract class or interface.

NoSuchMethodException Occurs when you call a method that


does not exist.

NIIT Programming in Java Lesson 1B / Slide 10 of 25


Exception Handling

Exceptions in Java (Contd.)


The following table lists the various unchecked exceptions:

Exception Cause of Creation

ArithmeticException Occurs when you make an


arithmetic error, such as dividing a
number by zero.

ArrayIndexOutOfBoundsException Occurs when an attempt is made to


access an array element beyond
the index of the array.

ArrayStoreException Occurs when you assign an


element to an array that is not
compatible with the data type of
that array.

NIIT Programming in Java Lesson 1B / Slide 11 of 25


Exception Handling

Exceptions in Java (Contd.)

Exception Cause of Creation

ClassCastException Occurs when you assign a


reference variable of a class to an
incompatible reference variable of
another class.

IllegalArgumentException Occurs when you pass an


argument of incompatible data
type to a method.

NegativeArraySizeException Occurs when you create an array


with negative size.

NIIT Programming in Java Lesson 1B / Slide 12 of 25


Exception Handling

Exceptions in Java (Contd.)

Exception Cause of Creation

NullPointerException Occurs when an application tries to


use an object without allocating
memory to it or calls a method of a
null object.

NumberFormatException Occurs when you want to convert a


string in an incorrect format to a
numeric format.

NIIT Programming in Java Lesson 1B / Slide 13 of 25


Exception Handling

Implementing Exception Handling


You can implement exception-handling in a program by using the following
keywords:
try
catch
throw
throws
finally
Using try and catch statements
The try block encloses the statements that might raise an exception
within it and defines the scope of the exception handlers associated
with it.
The catch block is used as an exception-handler. You enclose the code
that you want to monitor inside a try block to handle a run time error.

NIIT Programming in Java Lesson 1B / Slide 14 of 25


Exception Handling

Implementing Exception Handling


(Contd.)
The following syntax shows how to declare the try-catch block:
try
{
// Statements that cause an exception.
}
catch(ExceptionName obj)
{
// Error handling code.
}
Using multiple catch statements
A single try block can have many catch blocks. This is necessary when
the try block has statements that raise different types of exceptions.

NIIT Programming in Java Lesson 1B / Slide 15 of 25


Exception Handling

Implementing Exception Handling


(Contd.)
The multiple catch blocks generate unreachable code error.
If the first catch block contains the Exception class object then the
subsequent catch blocks are never executed.
The Exception class being the superclass of all the exception classes catches
various types of exceptions. The Java compiler gives an error stating that the
subsequent catch blocks have not been reached.
This is known as the unreachable code problem.
To avoid unreachable code error, the last catch block in multiple catch
blocks must contain the Exception class object.
Using the finally clause
The finally block is used to process certain statements, no matter whether
an exception is raised or not.

NIIT Programming in Java Lesson 1B / Slide 16 of 25


Exception Handling

Implementing Exception Handling


(Contd.)
The following syntax shows how to declare the try-finally
block:

try
{
// Block of code
}
finally
{
// Block of code that is always executed irrespective of
an exception being raised or not.
}

NIIT Programming in Java Lesson 1B / Slide 17 of 25


Exception Handling

Throwing an Exception
Using the throw statement
The throw statement causes termination of the normal flow of control of the
Java code and stops the execution of the subsequent statements if an exception
is thrown when the throw statement is executed.
The throw clause transfers the control to the nearest catch block handling the
type of exception object throws.
The following syntax shows how to declare the throw statement:
throw ThrowableObj
Using the throws statement
The throws statement is used by a method to specify the types of exceptions
the method throws.
If a method is capable of raising an exception that it does not handle, the
method must specify that the exception has to be handled by the calling
method.
This is done using the throws statement.

NIIT Programming in Java Lesson 1B / Slide 18 of 25


Exception Handling

Implementing User-Defined Exception


The user-defined Exception class also inherits the methods defined in the
Throwable class.
The following table lists the various methods defined by the Throwable class:

Methods Description

String getMessage() Returns a description of the


exception
String toString() Returns a string object containing a
description of the exception.

Throwable fillInStackTrace() Returns a Throwable object that


contains a stack trace

void printStackTrace() Prints the stack trace

NIIT Programming in Java Lesson 1B / Slide 19 of 25


Exception Handling

Demonstration-Exception Handling in
Java
Problem Statement

System Software Solutions Inc. needs to store the details, such as


name, age, and ID of three employees of the company. While
storing the details of the employees, the record of an employee
was entered twice and hence the record of the third employee
could not be displayed. Identify the exception that is raised if the
details of all the employees were stored. Use the try- catch block
to handle the exception.

NIIT Programming in Java Lesson 1B / Slide 20 of 25


Exception Handling

Demonstration-Exception Handling in
Java (Contd.)
Solution

To solve the above problem, perform the following tasks:


1. Identify the type of error and the code segment in which the
error occurs.
2. Identify the mechanism of trapping the exception.
3. Code the application
4. Compile and execute the application

NIIT Programming in Java Lesson 1B / Slide 21 of 25


Exception Handling

Assertions in Java
Assertions are the checks provided by the Java language to ensure that any
assumption made at the start of a program is true throughout the program.
Assertions:
Assertions are statements in Java that enable you to test the
assumptions made in a program during program execution.
An assertion statement contains a boolean expression that the
programmer believes to be true at the time the statement is executed.
Assertions are used during testing of a program to ensure that the
specified condition is true.
The following syntax shows how to declare an assertion using assert
statement in Java:
assert expressionA;
The following syntax shows the compilation of the Java program named
AssertDemo.java that is using assert statement:
javac -source 1.4 AssertDemo.java

NIIT Programming in Java Lesson 1B / Slide 22 of 25


Exception Handling

Assertions in Java (Contd.)


The syntax to enable assertion in a specified class with ea option is: .
java ea: AssertDemo
The syntax to disable assertion in a specified class with da option is:
java da: AssertDemo

NIIT Programming in Java Lesson 1B / Slide 23 of 25


Exception Handling

Summary
In this lesson, you learned:

Errors can be broadly categorized into two groups on the basis of


whether the compiler is able to handle the error or not, such as compile
time errors and run time errors.
An exception is a run time error that can be defined as an abnormal
event that occurs during the execution of a program and disrupts the
normal flow of instructions.
In Java, the Throwable class is the superclass of all the exception
classes. It is the class at the top position in the exception class hierarchy.
The Exception class and the Error class are two direct subclasses of the
Throwable class.
The built-in exceptions in Java are divided into two types on the basis of
the conditions where the exception is raised:
Checked Exceptions or Compiler-enforced Exceptions
Unchecked exceptions or Runtime Exceptions
NIIT Programming in Java Lesson 1B / Slide 24 of 25
Exception Handling

Summary (Contd.)
You can implement exception handling in your program by using the
following keywords:
try
catch
throw
throws
finally
You use multiple catch blocks to throw more than one type of exception.
The finally clause is used to execute the statements that need to be
executed whether or not an exception has been thrown.
The throw statement causes termination of the normal flow of control of
the Java code and stops the execution of subsequent statements after
the throw statement.
The throws clause is used by a method to specify the types of exceptions
the method throws.
You can create your own exception classes to handle the situations
specific to an application
NIIT Programming in Java Lesson 1B / Slide 25 of 25

You might also like