You are on page 1of 19

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

12/07/21 1
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

12/07/21 2
Exceptions in Java (Contd.)
• Exception Classes

• The following figure shows the Exception class heirarchy:

12/07/21 3
Exceptions in Java (Contd.)

12/07/21 4
Exceptions in Java (Contd.)
• Built-in Exceptions
• Java consists of the following categories of built-in exceptions:
• Checked Exceptions
• Unchecked Exceptions

12/07/21 5
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.

12/07/21 6
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.

12/07/21 7
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.

12/07/21 8
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.

12/07/21 9
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.

12/07/21 10
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.

12/07/21 11
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.

12/07/21 12
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.
}

12/07/21 13
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.

12/07/21 14
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

12/07/21 15
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.

12/07/21 16
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

12/07/21 17
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
12/07/21 18
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
12/07/21 19

You might also like