0% found this document useful (0 votes)
2 views32 pages

Exception Handling in Java With Examples (1)

This document provides a comprehensive overview of exception handling in Java, detailing the types of errors and exceptions, their causes, and the importance of handling them effectively. It explains the exception hierarchy, differences between checked and unchecked exceptions, and outlines the procedures for implementing exception handling using try-catch blocks. Additionally, it emphasizes the need for robust programming to manage exceptions and improve user experience by providing understandable error messages.

Uploaded by

ayushmaurya155
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views32 pages

Exception Handling in Java With Examples (1)

This document provides a comprehensive overview of exception handling in Java, detailing the types of errors and exceptions, their causes, and the importance of handling them effectively. It explains the exception hierarchy, differences between checked and unchecked exceptions, and outlines the procedures for implementing exception handling using try-catch blocks. Additionally, it emphasizes the need for robust programming to manage exceptions and improve user experience by providing understandable error messages.

Uploaded by

ayushmaurya155
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Exception Handling in Java with Examples

In this article, I am going to discuss Exception Handling in Java with Examples.


Whenever we develop any application there is a chance of occurring errors in
the application. As Java developers, it is our key responsibility to handle the
exception while developing an application. At the end of this article, you will
understand the following pointers in detail.

1. What is an Error?
2. Compile Time and Run time Errors
3. What is an Exception?
4. Why an exception occurs?
5. What happens when an exception is raised in the program?
6. What JVM does do when a logical mistake occurred in the
program?
7. Exception Hierarchy in Java
8. What are the differences between Error and Exception?
9. Types of Exceptions in Java
10.Checked and Unchecked Exceptions in Java
11.What is exception handling in Java?
12.Why do we need Exception Handling in Java?
13.How can we handle an exception in Java?
14.Multiple catch blocks in Java
15.Can we catch all exceptions using a single catch block?
16.When should we write multiple catch blocks for a single try
block?
17.How to display Exception or Runtime Error Message?

What is an Error?
An Error indicates a serious problem that a reasonable application should not
try to catch.
We have the following two types of errors:

1. Compile Time Error


2. Run Time Error
Compile Time Error
Errors that occur at the time of compilation of the program are called compile-
time errors. Compile-time errors occurred because if we don’t follow the java
syntaxes properly, java programming rules properly, etc. Compile-time errors
are identified by the java compiler. So in simple words, we can say that
compile-time errors occur due to a poor understanding of the programming
language. These errors can be identified by the programmer and can be
rectified before the execution of the program only. So these errors do not
cause any harm to the program execution.
Run Time Error
Errors that occur at the time of execution in the program are called runtime
errors. Run-Time Errors are also called Exceptions. Exceptions may occur
because programmer logic fails or JVM fails. Exceptions are identified by JVM.
Note: The Runtime errors are dangerous because whenever they occur in the
program, the program terminates abnormally on the same line where the error
gets occurred without executing the next line of code.
What is an Exception?
Exceptions are the run-time errors that occur during the execution of the
program. The exception will cause the abnormal termination of the program
execution.

An Exception is an unwanted event that interrupts the normal flow of the


program. When an exception occurs program execution gets terminated. It is
an object which is thrown at runtime.
Why an exception occurs?

These errors occurred when we enter the wrong data into a variable, try to
open a file for which there is no permission, try to connect to the database
with the wrong user id and password, the wrong implementation of logic,
missing required resources, etc.
There can be several reasons that can cause a program to throw an exception.
For example: Opening a non-existing file in your program, Network connection
problem, bad input data provided by the user, etc.
Why do we need Exception?
Suppose you have coded a program to access the server. Things worked fine
while you were developing the code.

During the actual production run, the server is down. When your program tried
to access it, an exception is raised.
How to Handle Exception
So far we have seen, exception is beyond developer’s control. But blaming your
code failure on environmental issues is not a solution. You need a Robust
Programming, which takes care of exceptional situations. Such code is known
as Exception Handler.
In our example, good exception handling would be, when the server is down,
connect to the backup server.

To implement this, enter your code to connect to the server (Using traditional if
and else conditions).
You will check if the server is down. If yes, write the code to connect to the
backup server.
Such organization of code, using “if” and “else” loop is not effective when your
code has multiple java exceptions to handle.
class connect{
if(Server Up){
// code to connect to server
}
else{
// code to connect to BACKUP server
}
}

What happens when an exception is raised in the program?

Program execution is terminated abnormally. It means statements placed after


exception-causing statements are not executed but the statements placed
before that exception-causing statements are executed by JVM.

What JVM does do when a logical mistake occurred in the program?

It creates an exception class object that is associated with that logical mistake
and terminates the current method execution by throwing this exception
object by using the “throw” keyword.

So we can say an exception is an event that occurs during the execution of a


program that disrupts the normal flow of instruction execution.

Example: The below example shows program execution without exception


public class ExceptionHandlingDemo
{
public static void main (String[]args)
{
int a = 20;
int b = 10;
System.out.println ("a value = " + a);
System.out.println ("b value = " + b);
int c = a / b;
System.out.println ("c value = " + c);
}
}
Output:

Example: The following example shows program execution with the


exception

public class ExceptionHandlingDemo


{
public static void main (String[]args)
{
int a = 20;
int b = 0;
System.out.println ("a value = " + a);
System.out.println ("b value = " + b);
int c = a / b;
System.out.println ("c value = " + c);
}
}
Output:

Explanation of the above Program:

After printing the value of a and b, JVM terminates this program execution by
throwing ArithmeticException because the logical mistake we committed is
dividing integer numbers by integer zero.

As we know it is not possible to divide an integer number by zero. But it is


possible to divide a number with double zero (0.0).

From the above program, we can define the exception technically as


1. An exception is an event because when an exception is raised JVM
internally executes some logic to prepare that exception-related
messages.
2. The exception is a signal because by looking into the exception
message developer will take necessary actions against that
exception.
3. An exception is an object because for throwing an exception, JVM
or we should create an appropriate class object.

Exception Hierarchy in Java

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

All exception and error types are subclasses of class Throwable, which is the
base class of the hierarchy.

One branch is headed by Exception. This class is used for exceptional conditions
that user programs should catch.
NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM) to indicate
errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.

A hierarchy of Java Exception classes is given below:

Here,

Object: Object is the super most class of all classes available in java.
Throwable: For all types of exceptions java.lang.Throwable is the superclass.
It has two main subclasses
1. Error
2. Exception
Exception: Exception is the super most class of all exceptions that may occur
because of programmer logic failure. These exceptions we can handle.
Error: Error is the super-most class of all exceptions that occur because of JVM
failure. These errors we cannot handle.

What are the differences between Error and Exception?

An Exception is an exception that can be handled. It means when an exception


happens the programmer can do something to avoid any harm. But an Error is
an exception that cannot be handled. It means it happens and the programmer
cannot do anything.
Let’s see in detail

Difference 1:
Error type exception is thrown due to the problem that occurred inside JVM
logic, like If there is no memory in the java stack area to create a new
Stackframe to execute method then the JVM process is killed by throwing Error
type exception “java.lang.StackOverfolwError”.

If there is no memory in the heap area to create a new object then the JVM
process is killed by throwing the Error type exception
“java.lang.OutOfMemoryError”.

Exception type exceptions are thrown due to the problem that occurred in java
program logic, like If we divide an integer number with zero, then JVM
terminates program execution by throwing Exception type exception
“java.lang.ArithmeticException”.

If we pass the array size as a negative number, then JVM terminates the
program execution by throwing the exception type exception
“java.lang.NegativeArraySizeException”.

Difference 2:
We cannot catch an Error type exception because an error type exception is not
thrown in our application and once this error type exception is thrown JVM is
terminated.
We can catch an Exception type exception because an exception type exception
is thrown in our program and moreover JVM is not directly terminated because
of an exception type exception. JVM is only terminated if the thrown exception
is not caught.
Types of Exceptions in Java:

We have the following two types of Exceptions:


1. Checked Exceptions
2. Unchecked Exceptions

Checked Exceptions in Java:


Exceptions that are identified at compilation time and occurred at runtime are
called checked exceptions. These checked exceptions are also called Compile
Time Exceptions.

An exception said to be checked exception whose exception handling is


mandatory as per the compiler.

Example:
IOException,
ClassNotFoundException,
CloneNotSupportedException, etc.

These are the exceptions that are checked at compile time. If some code within
a method throws a checked exception, then the method must either handle
the exception or it must specify the exception using the throws keyword.

In checked exceptions, there are two types: fully checked and partially checked
exceptions. A fully checked exception is a checked exception where all its child
classes are also checked, like IOException, and InterruptedException. A partially
checked exception is a checked exception where some of its child classes are
unchecked, like an Exception.

For example, consider the following Java program that opens the file at location
“C:\test\a.txt” and prints the first three lines of it.
The program doesn’t compile, because the function main() uses FileReader(),
and FileReader() throws a checked exception FileNotFoundException. It also
uses readLine() and close() methods, and these methods also throw checked
exception IOException

package checkedunchecked;
import java.io.FileReader;
public class Checkedunchecked
{
public static void main(String[] args)
{
ClassA a1 = new ClassA();
a1.f1();
FileReader file = new FileReader("somefile.txt");
}

Unchecked Exceptions in Java


Exceptions that are identified and occur at run-time are called Unchecked
Exceptions.
These Unchecked Exceptions are also called Runtime Exceptions. An exception
is said to be an unchecked exception whose exception handling is optional as
per the compiler.

These are the exceptions that are not checked at compile time. In C++, all
exceptions are unchecked, so it is not forced by the compiler’s to either handle
or specify the exception. It is up to the programmers to be civilized and specify
or catch the exceptions.

In Java, exceptions under Error and RuntimeException classes are unchecked


exceptions, everything else under throwable is checked.
Consider the following Java program. It compiles fine, but it
throws ArithmeticException when run. The compiler allows it to compile
because ArithmeticException is an unchecked exception.
Example:
Arithmetic Exception,
NumberFormatException,
NoSuchMethodError, etc.
Note: All child classes of Error and Runtime Exception classes are called
unchecked exceptions and the remaining classes are called checked exceptions.

Example of getting clarity about the exception:


Check the below program, in this program, there is a chance of raising three
exception
public class Division
{
public static void main (String[]args)
{
int a = Integer.parseInt (args[0]);
int b = Integer.parseInt (args[1]);
int c = a / b;
System.out.println ("Result : " + c);
}
}

Output:

Is the above exception messages user-understandable?


Definitely, no, users cannot understand the above exception messages because
they are java based on exception messages. So the user cannot take further
decisions alone to resolve the above problem. Developers should guide to solve
the above problem.

What is the solution to the above problem?

It is the developer’s responsibility to convert java exception messages into user-


understandable message format. To solve this problem developer should write
exception handling code in the java program. Using exception handling code,
developers can catch the exception and can print and pass user understandable
messages.

What is exception handling in Java?

The process of catching the exception for converting JVM given exception
message to end-user understandable message or for stopping the abnormal
termination of the program is called exception handling.

The process of handling these run-time errors or exceptions is called Exception


Handling.

Once we handle the exception in a program we will be getting the following


advantages
1. We can stop the abnormal termination
2. We can perform any corrective action that may resolve the
problem occurring due to abnormal termination.
3. Displaying a user-friendly error message, so that the client can
resolve the problem provided if it is under his control.

Why do we need Exception Handling in Java?


In projects, the exception is handled
1. To stop the abnormal termination of the program
2. To provide user understandable messages when an exception is
raised.

So that users can take decisions without the developer’s help.


Basically by implementing Exception handling, we are providing life to a
program to talk to the user on behalf of the developer.

What is the procedure to Handle Exception in Java?

The Exception Handling in Java is a 4 steps procedure


1. Preparing the exception object appropriate to the current logical
mistake.
2. Throwing that exception to the appropriate exception handler.
3. Catching that exception
4. Taking necessary actions against that exception

How can we handle an exception in Java?

There are two ways to handle the exception in Java.

1. Logical implementation
2. Try catch implementation

What is logical implementation?

In this method, we handle the exception by using logical statements. In real-


time programming, the first and foremost importance always given to logical
implementation only.
If it is not possible to handle the exception using logical implementation then
we only need to go for try-catch implementation.

import java.io.*;
public class Main
{
public static void main (String[]args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int a, b, c;
System.out.println("Enter Any 2 Numbers");
a = Integer.parseInt(br.readLine());
b = Integer.parseInt(br.readLine());

if (b == 0)
{
System.out.println("second number should not be zero");
}
else
{
c = a / b;
System.out.println("C VALUE = " + c);
}
}
}
Output:
In the above example when we entered the second number is zero, then the
exception will be raised and that is handled using logical implementation.
But while we are entering two numbers instead of the number if we entered
any character then it will give you one exception which is FormatException
which is not handled in this program as shown in the below image.

Whenever an exception has occurred within the particular method then the
corresponding exception object is created by the particular method and given
to JVM, then JVM will search for exception handling code within the particular
method if not available it will search in its caller method even there also it is
not available, then finally JVM will call “Default Exception Handler” Program
which will display the Exception object and terminate the method from java
stack (abnormal termination). In order to handle such a type of exception, we
need to go for Try catch implementation.
Exception handling in Java using the Try Catch implementation with
Examples

In Java, Exception Handling can be done by using five Java keywords:


1. Try
2. Catch
3. Finally
4. Throw
5. throws
Let us first understand how try-catch works and then we will proceed with the
rest three keywords.

Try block:
try keyword establishes a block in which we need to write the exception
causing and its related statements. That means exception-causing statements
must be placed in the try block so that we can handle and catch that exception
for stopping abnormal termination and to display end-user understandable
messages.

Catch block:
The catch block is used to catch the exception that is thrown from its
corresponding try block. It has logic to take necessary on that caught exception.
Catch block syntax is look like a constructor. It does not take accessibility
modifier, normal modifier, or return type.
It takes a single parameter of type Throwable or its subclasses. Throwable is
the superclass of all exception sub-classes. Inside the catch block, we can write
any statement which is legal in java including raising an exception. A try block
can be followed by multiple catch blocks.

Syntax to use Try Catch in Java:

Exception Handling Example in Java


Below program shows handling and catching exceptions to print user
understandable messages relevant to the thrown exception.
import java.io.*;
public class Main
{
public static void main (String[]args) throws IOException
{
try
{
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
int a, b, c;
System.out.println ("Enter Any 2 Numbers");
a = Integer.parseInt (br.readLine ());
b = Integer.parseInt (br.readLine ());
c = a / b;
System.out.println ("C VALUE = " + c);
}
catch (ArithmeticException ae)
{
System.out.println ("please dont pass the second value as 0");
}
}
}
Output:
Rules in using try Catch in java
1. Rule1: try must follow either zero or n number of catch blocks or 1
finally block else it leads to Compilation Error: “try without a catch
or finally”
2. Rule2: catch must be placed immediately after try block else it
leads to Compilation Error: “catch without try:”
3. Rule3: finally must be placed either immediately after try or after
try/catch else it leads to Compilation Error: “finally without try”
4. Rule4: the catch block parameter must be of type
java.lang.Throwable or its sub-classes else it leads to Compilation
Error: “incompatible types”
5. Rule5: try/catch/finally blocks are not allowed at the class level
directly because logic is not allowed at the class level directly.

Multiple catch blocks in Java:

It is possible in Java to write multiple catch blocks for a single try block. Check
the below program.
import java.io.*;
public class Main
{
public static void main (String[]args) throws IOException
{
try
{
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
int a, b, c;
System.out.println ("Enter Any 2 Numbers");
a = Integer.parseInt (br.readLine ());
b = Integer.parseInt (br.readLine ());
c = a / b;
System.out.println ("C VALUE = " + c);
}
catch (NumberFormatException nfe)
{
System.out.println ("please pass only integer values");
}
catch (ArithmeticException ae)
{
System.out.println ("please dont pass the second value as 0");
}
}
}
Output:
Note: After the try block, we can write multiple catch blocks to catch every
exception thrown from its corresponding try block.

Can we catch all exceptions using a single catch block?


Yes, we can catch all exceptions with a single catch block with the parameter
“java.lang.Exception” We should use this catch block only for stopping
abnormal termination irrespective of the exceptions thrown from its
corresponding try block. An example is given below.
import java.io.*;
public class Main
{
public static void main (String[]args) throws IOException
{
try
{
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
int a, b, c;
System.out.println ("Enter Any 2 Numbers");
a = Integer.parseInt (br.readLine ());
b = Integer.parseInt (br.readLine ());
c = a / b;
System.out.println ("C VALUE = " + c);
}
catch (Exception ex)
{
System.out.println (ex.getMessage());
}
}
}
Output:

It is always recommended to write catch blocks with exception parameters


even though we are writing multiple catch blocks. It acts as a backup catch
block.

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.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the
variable throws a NullPointerException.
String s=null;
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.
String s="abc";
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.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
When should we write multiple catch blocks for a single try block?

We should write multiple catch blocks for a single try block because of the
following reasons
1. To print a message specific to an exception or
2. To execute some logic specific to an exception
In our multiple catch block programs, we have placed catch blocks with
different exception classes to print messages relevant to the caught exception.
Rules for Writing Multiple catch block in java:

1. Rule1: catch block should not be duplicated.


2. Rule2: superclass parameter catch block should not be placed
before the child class parameter catch block. Violation of any of
the above rules leads to CE: “exception has already been caught”

Note: we write multiple catch blocks not only for printing exception-specific
messages but also for executing some logic specific to the exception raised in
the corresponding try statement.

Example: using multiple catch blocks along with generic catch block
import java.io.*;
public class Main
{
public static void main (String[]args) throws IOException
{
try
{
BufferedReader br = new BufferedReader (new InputStreamReader
(System.in));
int a, b, c;
System.out.println ("Enter Any 2 Numbers");
a = Integer.parseInt (br.readLine ());
b = Integer.parseInt (br.readLine ());
c = a / b;
System.out.println ("C VALUE = " + c);
}
catch (NumberFormatException nfe)
{
System.out.println ("please pass only integer values");
}
catch (ArithmeticException ae)
{
System.out.println ("please dont pass the second value as 0");
}
catch (Exception ex)
{
System.out.println ("Generic Exception");
}
}
}
Output:

How to display Exception or Runtime Error Message?


The throwable class has three methods to print the exception messages. These
methods are useful when we write catch blocks with a superclass as a
parameter. JVM printed Exception message format is shown below.
Using printStackTrace():
If we use the printstackTrace() method it will display the Exception information
in detail like reason, Exception class name, program name where it has
occurred, in what method, and in what line.

Using toString():
If we use the toString() method it will display the reason why the Exception has
occurred and the Exception class name.

Using getMessage():
If we use the getMessage() method it will display only the reason why the
Exception has occurred.

Below example shows calling the above three methods:


public class Main
{
public static void main (String[]args)
{
try
{
System.out.println (10 / 0);
}
catch (ArithmeticException ae)
{
System.out.println ("getMessage method output");
System.out.println (ae.getMessage ());
System.out.println ("toString method output");
System.out.println (ae.toString ());
System.out.println ("printStackTrace() method output");
ae.printStackTrace ();
System.out.println ("JVM default output");
throw ae;

//by using above statement we are just re-throwing the caught exception this
//exception is caught by JVM default handler and prints full exception
messages
//along with thread name
}
}
}
Output:
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The
following table describes each.

Keyword Description

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


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

catch The "catch" block is used to handle the exception. It


must be preceded by try block 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 necessary 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


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

You might also like