You are on page 1of 23

Java - Exceptions

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.
Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:

Types of Exception in Java

PAGE \* MERGEFORMAT 1 | Java Exception Handling


In Java, exception is an event that occurs during the execution of a program and
disrupts the normal flow of the program's instructions. Bugs or errors that we don't want
and restrict our program's normal execution of code are referred to as exceptions. In
this section, we will focus on the types of exceptions in Java and the differences
between the two.

Exceptions can be categorized into two ways:

1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
2. User-Defined Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at
compile-time.

PAGE \* MERGEFORMAT 1 | Java Exception Handling


2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Difference Between Checked and Unchecked Exception


S.No Checked Exception Unchecked Exception

These exceptions are checked at compile time. These exceptions are just opposite to the checked
1. These exceptions are handled at compile time exceptions. These exceptions are not checked and
too. handled at compile time.

These exceptions are direct subclasses of


They are the direct subclasses of the
2. exception but not extended from
RuntimeException class.
RuntimeException class.

The code gives a compilation error in the case The code compiles without any error because the
when a method throws a checked exception. exceptions escape the notice of the compiler.
3.
The compiler is not able to handle the These exceptions are the results of user-created
exception on its own. errors in programming logic.

These exceptions mostly occur when the These exceptions occur mostly due to
4.
probability of failure is too high. programming mistakes.

Common checked exceptions include Common unchecked exceptions include


5. IOException, DataAccessException, ArithmeticException, InvalidClassException,
InterruptedException, etc. NullPointerException, etc.

These exceptions are propagated using the


6. These are automatically propagated.
throws keyword.

It is required to provide the try-catch and try- In the case of unchecked exception it is not
7.
finally block to handle the checked exception. mandatory.

Java - Built-in Exceptions


Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs, most
exceptions derived from RuntimeException are automatically available.

PAGE \* MERGEFORMAT 1 | Java Exception Handling


Java defines several other types of exceptions that relate to its various class
libraries. Following is the list of Java Unchecked RuntimeException.

Sr.No. Exception & Description

1
ArithmeticException
Arithmetic error, such as divide-by-zero.

2
ArrayIndexOutOfBoundsException
Array index is out-of-bounds.

3
ArrayStoreException
Assignment to an array element of an incompatible type.

4
ClassCastException
Invalid cast.

5
IllegalArgumentException
Illegal argument used to invoke a method.

6
IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked thread.

7
IllegalStateException
Environment or application is in incorrect state.

8
IllegalThreadStateException
Requested operation not compatible with the current thread state.

9
IndexOutOfBoundsException
Some type of index is out-of-bounds.

10
NegativeArraySizeException

PAGE \* MERGEFORMAT 1 | Java Exception Handling


Array created with a negative size.

11
NullPointerException
Invalid use of a null reference.

12
NumberFormatException
Invalid conversion of a string to a numeric format.

13
SecurityException
Attempt to violate security.

14
StringIndexOutOfBounds
Attempt to index outside the bounds of a string.

15
UnsupportedOperationException
An unsupported operation was encountered.

Following is the list of Java Checked Exceptions Defined in java.lang.

Sr.No. Exception & Description

1
ClassNotFoundException
Class not found.

2
CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.

3
IllegalAccessException
Access to a class is denied.

PAGE \* MERGEFORMAT 1 | Java Exception Handling


4
InstantiationException
Attempt to create an object of an abstract class or interface.

5
InterruptedException
One thread has been interrupted by another thread.

6
NoSuchFieldException
A requested field does not exist.

7
NoSuchMethodException
A requested method does not exist.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description

The "try" keyword is used to specify a block where we should place an


try exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.

The "catch" block is used to handle the exception. It must be preceded by


catch try block which means we can't use catch block alone. It can be followed by
finally block later.

The "finally" block is used to execute the necessary code of the program. It
finally
is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

The "throws" keyword is used to declare exceptions. It specifies that there


throws may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.

Exceptions Methods
Following is the list of important methods available in the Throwable class.

Sr.No. Method & Description

PAGE \* MERGEFORMAT 1 | Java Exception Handling


1
public String getMessage()
Returns a detailed message about the exception that has occurred.
This message is initialized in the Throwable constructor.

2
public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.

3
public String toString()
Returns the name of the class concatenated with the result of getMessage().

4
public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.

5
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the
method at the bottom of the call stack.

6
public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException

PAGE \* MERGEFORMAT 1 | Java Exception Handling


2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into NumberFormatException.
Suppose we have a string variable that has characters; converting this variable into digit will cause
NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other
reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

Different approaches to handle exceptions in Java.

 try...catch block
 finally block
 throw and throws keyword

1. Java try...catch block

The try-catch block is used to handle exceptions in Java. Here's the syntax
of try...catch block:

try {
// code
}
catch(Exception e) {
// code
}

Here, we have placed the code that might generate an exception inside the try block. Every try block is
followed by a catch block.

PAGE \* MERGEFORMAT 1 | Java Exception Handling


When an exception occurs, it is caught by the catch block. The catch block cannot be used without
the try block.

Example: Exception handling using try...catch

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

try {

// code that generate exception


int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}

Output

ArithmeticException => / by zero

2. Java finally block

In Java, the finally block is always executed no matter whether there is an exception

or not.
The finally block is optional. And, for each try block, there can be only

one finally block.

The basic syntax of finally block is:

try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes

PAGE \* MERGEFORMAT 1 | Java Exception Handling


}

If an exception occurs, the finally block is executed after the try...catch block.

Otherwise, it is executed after the try block. For each try block, there can be only

one finally block.

Example: Java Exception Handling using finally block

class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}

finally {
System.out.println("This is the finally block");
}
}
}

Output

ArithmeticException => / by zero


This is the finally block

In the previous page example, we are dividing a number by 0 inside the try block. Here, this

code generates an ArithmeticException.

The exception is caught by the catch block. And, then the finally block is executed.

Note: It is a good practice to use the finally block. It is because it can include important

cleanup codes like,

 code that might be accidentally skipped by return, continue or break

 closing a file or connection

PAGE \* MERGEFORMAT 1 | Java Exception Handling


Example

public class ExcepTest {

public static void main(String args[]) {


int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
This will produce the following result −
Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note the following −
 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block is present.
 The try block cannot be present without either catch clause or finally clause.
 Any code cannot be present in between the try, catch, finally blocks.

3. Java throw and throws keyword


The Java throw keyword is used to explicitly throw a single exception.

When we throw an exception, the flow of the program moves from the try block to

the catch block.

Example: Exception handling using Java throw

class Main {
public static void divideByZero() {

// throw an exception
throw new ArithmeticException("Trying to divide by 0");

PAGE \* MERGEFORMAT 1 | Java Exception Handling


}

public static void main(String[] args) {


divideByZero();
}
}

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by


0
at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)

Example: Java throws keyword


import java.io.*;

class Main {
// declareing the type of exception
public static void findFile() throws IOException {

// code that may generate IOException


File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
}

public static void main(String[] args) {


try {
findFile();
}
catch (IOException e) {
System.out.println(e);
}
}
}

Output

java.io.FileNotFoundException: test.txt (The system cannot find the file


specified)

PAGE \* MERGEFORMAT 1 | Java Exception Handling


When we run this program, if the file test.txt does not
exist, FileInputStream throws a FileNotFoundException which extends
the IOException class.
The findFile() method specifies that an IOException can be thrown.
The main() method calls this method and handles the exception if it is thrown.
If a method does not handle exceptions, the type of exceptions that may occur
within it must be specified in the throws clause.

More on The Throws/Throw Keywords


If a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a method's
signature.
You can throw an exception, either a newly instantiated one or an exception that you
just caught, by using the throw keyword.
Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
The following method declares that it throws a RemoteException −
Example
import java.io.*;
public class className {

public void deposit(double amount) throws RemoteException {


// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the
exceptions are declared in a list separated by commas. For example, the following
method declares that it throws a RemoteException and an InsufficientFundsException −
Example
import java.io.*;
public class className {

public void withdraw(double amount) throws RemoteException,

PAGE \* MERGEFORMAT 1 | Java Exception Handling


InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}
Java Throw Keyword

It is a keyword that is used to explicitly throw an exception.


We can use throw where according to our logic an exception should occur.
Example:

Output:

Java Throws Keyword


 Throws keyword is used when callee doesn’t want to handle the exception rather it
wants to extend this responsibility of handling the exception to the caller of the
function.
 Basically says what sort of exception the code can throw and relies on the caller to
handle it.
 It is used to handle checked Exceptions as the compiler will not allow code to
compile until they are handled.

PAGE \* MERGEFORMAT 1 | Java Exception Handling


Example:

Output:

If callee can throw multiple exceptions, then all will be thrown simultaneously.

PAGE \* MERGEFORMAT 1 | Java Exception Handling


Multiple Catch blocks
For each try block, there can be zero or more catch blocks. Multiple catch blocks allow us to
handle each exception differently.

PAGE \* MERGEFORMAT 1 | Java Exception Handling


The argument type of each catch block indicates the type of exception that can be handled by it.
For example,
class ListOfNumbers {
public int[] arr = new int[10];

public void writeList() {

try {
arr[10] = 11;
}

catch (NumberFormatException e1) {


System.out.println("NumberFormatException => " + e1.getMessage());
}

catch (IndexOutOfBoundsException e2) {


System.out.println("IndexOutOfBoundsException => " + e2.getMessage());
}

}
}

class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}

PAGE \* MERGEFORMAT 1 | Java Exception Handling


PAGE \* MERGEFORMAT 1 | Java Exception Handling
PAGE \* MERGEFORMAT 1 | Java Exception Handling
User-defined Exceptions
You can create your own exceptions in Java. Keep the following points in mind when
writing your own exception classes −
 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is automatically enforced by the
Handle or Declare Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the
RuntimeException class.
We can define our own Exception class as below –
class MyException extends Exception {
}
You just need to extend the predefined Exception class to create your own Exception.
These are considered to be checked exceptions. The
following InsufficientFundsException class is a user-defined exception that extends
the Exception class, making it a checked exception. An exception class is like any other
class, containing useful fields and methods.
Example
// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception {


private double amount;

public InsufficientFundsException(double amount) {


this.amount = amount;
}

public double getAmount() {

PAGE \* MERGEFORMAT 1 | Java Exception Handling


return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount class
contains a withdraw() method that throws an InsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount {


private double balance;
private int number;

public CheckingAccount(int number) {


this.number = number;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) throws InsufficientFundsException {


if(amount <= balance) {
balance -= amount;
}else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}

public double getBalance() {


return balance;
}

public int getNumber() {


return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.
// File Name BankDemo.java
public class BankDemo {

public static void main(String [] args) {


CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);

PAGE \* MERGEFORMAT 1 | Java Exception Handling


try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo. This will produce the following
result −
Output
Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

Java Nested Try


When there is another try block within the try block:

class Main {
public static void main (String[] args) {
try{
try{
int[] a={1,2,3};
System.out.println(a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Out of bounds");
}
System.out.println(4/0);
}
catch(ArithmeticException e)

PAGE \* MERGEFORMAT 1 | Java Exception Handling


{
System.out.println("ArithmeticException : divide by 0");
}
}
}

Output:
Out of bounds
ArithmeticException: Divide by 0

Java Final vs Finally vs Finalize


Final Finally Finalize

Final is used to apply Finally is used in coding, it will be Finalize is used to perform clean-
restrictions on class, method, executed whether an exception is up processing before garbage is
and variable handled or not. collected.

Final is a keyword in java Finally is a block in java Finalize is a method in java

Finally executes after”try-catch” finalize executes just before the


Final is executed upon its call.
block. destruction of the object.

PAGE \* MERGEFORMAT 1 | Java Exception Handling

You might also like