U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
3.1 Exception Handling in Java
• The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
Advantage of Exception Handling
• The core advantage of exception handling is to maintain the normal flow of the application.
• An exception normally disrupts the normal flow of the application that is why we use
exception handling.
Exception
• Exception is an abnormal condition.
• An exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime
• IOException is usually a case in which the user inputs improper data into the program.
o Read the file which is not available
• An exception that provides information on a database access error or other errors
o Java Exception message, available via the method getMesasge .
• ClassNotFoundException is a checked exception in Java that occurs when the JVM tries to load
a particular class but does not find it in the classpath
• RuntimeException is the superclass of those exceptions that can be thrown during the normal
operation of the Java Virtual Machine.
o Thrown when an exceptional arithmetic condition has occurred. For example, an integer
"divide by zero" throws an instance of this class. ArithmeticException objects may be
constructed by the virtual machine as if suppression were disabled and/or the stack trace
was not writable.
Ex: c=5/0;
o NullPointerException is a RuntimeException. In Java, a special null value can be
assigned to an object reference.
Ex: String a=null;
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 1
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
o NumberFormatException, indicate that the application has attempted to convert a string
to one of the numeric types, but that the string does not have the appropriate format.
o IndexOutofBoundException
▪ ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at
runtime. The Java Compiler does not check for this error during the compilation
of a program.
Ex: int a[]=new int[5];
A[7]=9;
▪ StringIndexOutOfBoundsException is one of the unchecked exceptions in Java.
A string is kind of an ensemble of characters. String object has a range of [0,
length of the string]. When someone tries to access the characters with limits
exceeding the range of actual string value, this exception occurs.
Ex: String a=”hai”;
Char c=[Link](24);
Errors
• Error refers to an illegal operation performed by the user which results in the abnormal
working of the program.
• StackOverflowError
o Runtime error which points to serious problems that cannot be caught by an
application.
o The java. lang. StackOverflowError indicates that the application stack is exhausted
and is usually caused by deep or infinite recursion.
o Throws when the amount of stack memory is exceeded
• VirtualMachineError
o Indicate that the Java Virtual Machine is broken or has run out of resources necessary
for it to continue operating(Resource limitation)
• OutOfMemoryError
o Runtime error in Java which occurs when the Java Virtual Machine (JVM) is unable to
allocate an object due to insufficient space in the Java heap.
o Too many programs running at a time
o The Java Garbage Collector (GC) cannot free up the space required for a new object,
which causes a java
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 2
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
3.1.1 Exception Hierarchy
Types of Java Exceptions
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 3
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Keyword Description
try The “try” keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It means,
we can’t use try block alone.
The “catch” block is used to handle the exception. It must be preceded by try block
Catch
which means we can’t use catch block alone. It can be followed by finally block later.
Finally The “finally” block is used to execute the important code of the program. It is executed
whether an exception is handled or not.
Throw The “throw” keyword is used to throw an exception.
Throws The “throws” keyword is used to declare exceptions. It doesn’t throw an
exception. It specifies that there may occur an exception in the method. It is always
used with method signature.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 4
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
3.1.2 Build-in Exceptions
1. Arithmetic exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
// Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo {
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
[Link](“Result = “ + c);
}
catch (ArithmeticException e) {
[Link]("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0
2. ArrayIndexOutOfBounds Exception
It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
// Java program to demonstrate
// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 5
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found.
// Java program to illustrate the
// concept of ClassNotFoundException
class Bishal
{
}
class Geeks
{
}
class MyClass
{
public static void main(String[] args)
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 6
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
{
Object o = [Link](args[0]).newInstance();
[Link]("Class created for" + [Link]().getName());
}
}
Output:
ClassNotFoundException
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
Example:
import [Link];
import [Link];
import [Link];
class File_notFound_Demo {
public static void main(String args[])
{
try {
// Following file does not exist
File file = new File("E:// [Link]");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e) {
[Link]("File does not exist");
}
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 7
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
}
}
Output:
File does not exist
5. IOException
It is thrown when an input-output operation failed or interrupted
import [Link].*;
class Geeks {
public static void main(String args[])
{
FileInputStream f = null;
f = new FileInputStream("[Link]");
int i;
while ((i = [Link]()) != -1) {
[Link]((char)i);
}
[Link]();
}
}
Output:
error: unreported exception IOException; must be caught or declared to be thrown
6. InterruptedException :
It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
class Geeks {
public static void main(String args[])
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 8
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
{
Thread t = new Thread();
[Link](10000);
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
7. NoSuchMethodException
It is thrown when accessing a method which is not found.
NoSuchMethodException
class Geeks {
public Geeks()
{
Class i;
try {
i = [Link]("[Link]");
try {
Class[] p = new Class[5];
}
catch (SecurityException e) {
[Link]();
}
catch (NoSuchMethodException e) {
[Link]();
}
}
catch (ClassNotFoundException e) {
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 9
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
[Link]();
}
}
public static void main(String[] args)
{
new Geeks();
}
}
Output:
error: exception NoSuchMethodException is never thrown in body of corresponding try statement
8. NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
// Java program to demonstrate NullPointerException
class NullPointer_Demo {
public static void main(String args[])
{
try {
String a = null; // null value
[Link]([Link](0));
}
catch (NullPointerException e) {
[Link]("NullPointerException..");
}
}
}
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 10
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
Output:
NullPointerException..
9. NumberFormatException :
This exception is raised when a method could not convert a string into a numeric format.
// Java program to demonstrate
// NumberFormatException
class NumberFormat_Demo {
public static void main(String args[])
{
try {
// "akki" is not a number
int num = [Link]("akki");
[Link](num);
}
catch (NumberFormatException e) {
[Link]("Number format exception");
}
}
}
Output:
Number format exception
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 11
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
10. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size
of the string.
// Java program to demonstrate
// StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
String a = "This is like chipping "; // length is 22
char c = [Link](24); // accessing 25th element
[Link](c);
}
catch (StringIndexOutOfBoundsException e) {
[Link]("StringIndexOutOfBoundsException");
}
}
}
Output:
StringIndexOutOfBoundsException
3.1.3 Creating your own exception
• Create our own exceptions that are derived classes of the Exception class.
• Creating our own Exception is known as custom exception or user-defined exception.
• Java custom exceptions are used to customize the exception according to user need.
Why use custom exceptions?
o To catch and provide specific treatment to a subset of existing Java exceptions.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 12
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
o Business logic exceptions:
o Exceptions related to business logic and workflow.
o It is useful for the application users or the developers to understand the exact problem.
In order to create custom exception, we need to extend Exception class that belongs to [Link]
package.
Example:
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote");
}
else {
[Link]("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 13
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
}
catch (InvalidAgeException ex)
{
[Link]("Caught the exception");
// printing the message from InvalidAgeException object
[Link]("Exception occured: " + ex);
}
[Link]("rest of the code...");
}
}
3.2 Chained Exceptions in Java
• In Java, a chained exception is a technique that enables programmers to associate one Exception with
another. By providing additional information about a specific exception, debugging can be made easier.
• A chained exception is created by wrapping an existing exception in a new exception, which becomes
the root cause of the new Exception.
• The new Exception can provide additional information, while the original Exception contains the actual
error message and stack trace. It makes it easier to determine and fix the problem's source.
• Chained exceptions are especially useful when an exception is thrown due to another exception.
• In Java, a chained exception is created using one of the constructors of the exception class.
Throwable Class
• Constructors and methods for supporting chained exceptions are available in the Throwable class. Let's
start by taking a look at the constructors.
• Throwable(Throwable cause): A Java constructor creates a new exception object with a specified cause
exception.
• Throwable(String desc, Throwable cause): A Java constructor creates a new Throwable object with a
message and a cause. It allows for chaining exceptions and providing more detailed information about
errors.
• In Java, the following Throwable class methods enable chained exceptions:
• getCause(): It is a Java method of the Throwable class that returns the cause of the current Exception. It
allows for accessing the Exception or error that triggered the current Exception to be thrown.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 14
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
• initCause() method: determines the reason for the calling Exception.
Example of Chained Exception:
Filename: [Link]
public class ChainedExceptionExample {
public static void main(String[] args) {
try {
String s = null;
int num = [Link](s); // the line will throw a NumberFormatException
} catch (NumberFormatException e) {
// create a new RuntimeException with the message "Exception."
RuntimeException ex = new RuntimeException("Exception");
// set the cause of the new Exception to a new NullPointerException with the message " It is actual
cause of the exception "
[Link](new NullPointerException("It is actual cause of the exception"));
// throw the new Exception with the chained Exception
throw ex;
}
}
}
Output:
Exception in thread "main" [Link]: Exception at
[Link]([Link])
Caused by: [Link]: It is actual cause of the exception at
[Link]([Link])
3. STACK TRACE
• The stack trace is an array of stack frames/ stack backtrace (or backtrace).
• The stack frames represent the movement of an application during the execution of the
program.
• It traces the locations where exception raised.
• It collects the information of all the methods that are invoked by a program.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 15
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
• When we do not care about the unhandled exceptions and the program throws the exceptions
then Java stack trace prints the stack trace on the console by default.
• The JVM automatically produces the stack trace when an exception is thrown.
• In stack trace, each element represents a method invocation.
• The StackTraceElement class provides a constructor that parses four parameters as an
argument and creates a stack trace element that denotes the specified execution point.
public StackTraceElement(String declaringClass, String methodName, String fileName, int lineNum
ber)
Parameters:
o declaringClass: the qualified name of the class that contains the execution point.
o methodName: It represents the method name t hat contains the execution point.
o fileName: It represents the file name that contains the execution point.
o lineNumber: It represents the line number of the source of the execution point.
It throws the NullPointerException if the parameters declaringClass and methodName are null.
Textual representation (syntax) of the stack trace.
The first line denotes:
Exception in thread "main" [Link]: Fictitious NullPointerException at
ClassName.methodName1([Link]:lineNumber)
at ClassName.methodName2([Link]:lineNumber) at
ClassName.methodName3([Link]:lineNumber) at
[Link]([Link]:lineNumber)
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 16
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 17
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
The other line(s) denotes:
Example
public class StackTraceExample
public static void main(String args[])
demo();
static void demo()
demo1();
static void demo1()
demo2();
static void demo2()
demo3();
static void demo3() OUTPUT:
[Link](“Hello”);
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 18
U21CSG04-
Java Programming [UNIT III – EXCEPTION HANDLING]
At the first line of the stack trace, we get the execution point of the stack and from second line to the
end line we get the stack frames that form the complete stack trace. We see that the method executed
first becomes the last stack frame of the stack trace and the method executed at last becomes the first
stack frame of the stack trace. Therefore, each element of the stack trace represents a stack frame.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 19