Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

Exception Handling in Java

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.

What is Exception in Java?


In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

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 need to handle exceptions. Let's consider a scenario

1. statement 1;  
2. statement 2;  
3. statement 3;  
4. statement 4;  
5. statement 5; //exception occurs  
6. statement 6;  
7. statement 7;  
8. statement 8;  
9. statement 9;  
10. statement 10;  

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not
be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling
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 Java 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
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked
Exceptions
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.

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.

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.
Exception models :
In java, there are two exception models. Java programming language has two models of
exception handling. The exception models that java suports are as follows.

 Termination Model
 Resumptive Model

Let's look into details of each exception model.

Termination Model
The Java exception handling facility supports the termination model. In the
termination model, when a method encounters an exception, further processing in
that method is terminated and control is transferred to the nearest exception handler
that can handle the type of exception encountered. It’s important to note that this
doesn’t necessarily mean the entire program is terminated. It depends on what
action the exception handler performs and where the exception handler is in the call
chain

Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the
exception handler is expected to do something to stable the situation, and then the faulting
method is retried. In resumptive model we hope to continue the execution after the exception
is handled.
In resumptive model we may use a method call that want resumption like behavior. We may
also place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.

Uncaught Exceptions in Java


In java, assume that, if we do not handle the exceptions in a program. In this case, when an exception
occurs in a particular function, then Java prints a exception message with the help of uncaught
exception handler.

The uncaught exceptions are the exceptions that are not caught by the compiler but

automatically caught and handled by the Java built-in exception handler.


Java programming language has a very strong exception handling mechanism. It allow us to

handle the exception use the keywords like try, catch, finally, throw, and throws.

When an uncaught exception occurs, the JVM calls a special private method

known dispatchUncaughtException( ), on the Thread class in which the exception occurs

and terminates the thread.

Ex :
Exception handling :
Here's a list of different approaches to handle
exceptions in Java.

1. try...catch block
2. finally block
3. throw and throws keyword

1. Java try...catch block


 Here, we have placed the code that might
generate an exception inside the try block.
 When an exception occurs, it is caught by
the catch block. The catch block cannot be
used without the try
 when an exception occurs, the rest of the
code inside the try block is skipped.
 The catch block catches the exception and
statements inside the catch block is
executed.
 If none of the statements in the try block
generates an exception, the catch block is
skipped.
Example :
block.class Main {
public static void main(String[] args) {

try {
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException
division by zero " );
}
}
}
Output :
Arithmetic exception division 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.
 If an exception occurs, the finally block is
executed after the try...catch block.
Otherwise, it is executed after the try
block.
Example :
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException
division by zero “);
}
finally {
System.out.println("This is the finally
block");
}
}
}
Output :
ArithmeticException division by zero
This is the finally block

In the above 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.

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.
Ex for throw :
class Main {
public static void divideByZero() {
throw new ArithmeticException("Trying to
divide by 0");
}
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)

Similarly, the throws keyword is used to


declare the type of exceptions that might
occur within the method. It is used in the
method declaration.
Ex for throws keyword :
import java.io.*;
class Main {
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)
Java Catch Multiple Exceptions
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.

Points to remember
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch
for ArithmeticException must come before catch for Exception.

Flowchart of Multi-catch Block


Example 1
Let's see a simple example of java multi-catch block.

MultipleCatchBlock1.java

1. public class MultipleCatchBlock1 {  
2.   
3.     public static void main(String[] args) {  
4.           
5.            try{    
6.                 int a[]=new int[5];    
7.                 a[5]=30/0;    
8.                }    
9.                catch(ArithmeticException e)  
10.                   {  
11.                    System.out.println("Arithmetic Exception occurs");  
12.                   }    
13.                catch(ArrayIndexOutOfBoundsException e)  
14.                   {  
15.                    System.out.println("ArrayIndexOutOfBounds Exception occurs");  
16.                   }    
17.                catch(Exception e)  
18.                   {  
19.                    System.out.println("Parent Exception occurs");  
20.                   }             
21.                System.out.println("rest of the code");    
22.     }  
23. }  

Output:00:00/05:19

Arithmetic Exception occurs


rest of the code
Java Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested
try block. Every statement that we enter a statement in try block, context of that
exception is pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to
be nested.

NestedTryBlock.java

1. public class NestedTryBlock{    
2.  public static void main(String args[]){   
3.  //outer try block   
4.   try{    
5.   //inner try block 1  
6.     try{    
7.      System.out.println("going to divide by 0");    
8.      int b =39/0;    
9.    }  
10.     //catch block of inner try block 1  
11.     catch(ArithmeticException e)  
12.     {  
13.       System.out.println(e);  
14.     }    
15.        
16.     
17.     //inner try block 2  
18.     try{    
19.     int a[]=new int[5];    
20.   
21.     //assigning the value out of array bounds  
22.      a[5]=4;    
23.      }  
24.   
25.     //catch block of inner try block 2  
26.     catch(ArrayIndexOutOfBoundsException e)  
27.     {  
28.        System.out.println(e);  
29.     }    
30.   
31.       
32.     System.out.println("other statement");    
33.   }  
34.   //catch block of outer try block  
35.   catch(Exception e)  
36.   {  
37.     System.out.println("handled the exception (outer catch)");  
38.   }    
39.     
40.   System.out.println("normal flow..");    
41.  }    
42. }  

Output:

.
Built-in exceptions :
Built-in exceptions are the exceptions which are available in
Java libraries. These exceptions are suitable to explain certain
error situations. Below is the list of important built-in
exceptions in Java.
Examples of Built-in Exception:

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
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0
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[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds

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)
{
Object o = class.forName(args[0]).newInstance();
System.out.println("Class created for" +
o.getClass().getName());
}
}
Output:
ClassNotFoundException
FileNotFoundException : This Exception is raised when a file
is not accessible or does not open.
// Java program to demonstrate
// FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {

public static void main(String args[])


{
try {

// Following file does not exist


File file = new File("E:// file.txt");

FileReader fr = new FileReader(file);


}
catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
Output:
File does not exist
IOException : It is thrown when an input-output operation
failed or interrupted

// Java program to illustrate IOException


import java.io.*;
class Geeks {
public static void main(String args[])
{
FileInputStream f = null;
f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1) {
System.out.print((char)i);
}
f.close();
}
}
Output:
error: unreported exception IOException; must be caught or
declared to be thrown
Creating Own Exceptions in Java

 The Java programming language allow us to create our


own exception classes which are basically subclasses
built-in class Exception.

 To create our own exception class simply create a class


as a subclass of built-in Exception class.

 We may create constructor in the user-defined


exception class and pass a string to Exception class
constructor using super(). We can use getMessage()
method to access the string.

Example :

class CustomException extends Exception {


   String message;
   CustomException(String str) {
      message = str;
   }
   public String toString() {
      return ("Custom Exception Occurred : " + message);
   }
}
public class MainException {
   public static void main(String args[]) {
      try {
         throw new CustomException("This is a custom message");
      } catch(CustomException e) {
         System.out.println(e);
   }
   }
}

Output :
Custom Exception Occurred : This is a custom message

Differences between thread-based multitasking and process-based multitasking :

Process-Based Multitasking Thread-Based Multitasking

In process-based multitasking,
two or more processes and
programs can be run In thread-based multitasking, two or more
concurrently. threads can be run concurrently.

In process-based multitasking, a
process or a program is the In thread-based multitasking, a thread is
smallest unit. the smallest unit.

The program is a bigger unit. Thread is a smaller unit.

Process-based multitasking Thread-based multitasking requires less


requires more overhead. overhead.

The process requires its own


address space. Threads share the same address space.

The process to Process Thread to Thread communication is not


communication is expensive. expensive.

Here, it is unable to gain access It allows taking gain access over idle time
over the idle time of the CPU. taken by the CPU.
Process-Based Multitasking Thread-Based Multitasking

It is a comparatively
heavyweight. It is comparatively lightweight.

It has a faster data rate multi-


tasking because two or more
processes/programs can be run It has a comparatively slower data rate
simultaneously. multi-tasking.

Example: Using a browser we can


navigate through the webpage and at the
same time download a file. In this
example, navigation is one thread, and
Example: We can listen to downloading is another thread. Also in a
music and browse the internet word-processing application like MS
at the same time. The Word, we can type text in one thread, and
processes in this example are spell checker checks for mistakes in
the music player and browser.  another thread. 

Thread Concept in Java


Before introducing the thread concept, we were unable to run more than one task in
parallel. It was a drawback, and to remove that drawback, Thread Concept was
introduced.

A Thread is a very light-weighted process, or we can say the smallest part of the
process that allows a program to operate more efficiently by running multiple tasks
simultaneously.

In order to perform complicated tasks in the background, we used the Thread


concept in Java. All the tasks are executed without affecting the main program. In a
program or process, all the threads have their own separate path for execution, so
each thread of a process is independent.
Another benefit of using thread is that if a thread gets an exception or an error at
the time of its execution, it doesn't affect the execution of the other threads. All the
threads share a common memory and have their own stack, local variables and
program counter. When multiple threads are executed in parallel at the same time,
this process is known as Multithreading

.
41.5M

814

How to find Nth Highest Salary in SQL

In a simple way, a Thread is a:

o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.

Thread Model
Just like a process, a thread exists in several states. These states are as follows:

1) New (Ready to run)

A thread is in New when it gets CPU time.

2) Running

A thread is in a Running state when it is under execution.

3) Suspended

A thread is in the Suspended state when it is temporarily inactive or under execution.

4) Blocked

A thread is in the Blocked state when it is waiting for resources.

5) Terminated

A thread comes in this state when at any given time, it halts its execution
immediately.

Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or
by extending the Thread class. These are the only two ways through which we can
create a thread.
Let's dive into details of both these way of creating a thread:

Thread Class
A Thread class has several methods and constructors which allow us to perform
various operations on a thread. The Thread class extends the Object class.
The Object class implements the Runnable interface. The thread class has the
following constructors that are used to perform various operations.

o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Runnable Interface(run() method)


The Runnable interface is required to be implemented by that class whose instances
are intended to be executed by a thread. The runnable interface gives us
the run() method to perform an action for the thread.

start() method
The method is used for starting a thread that we have newly created. It starts a new
thread with a new callstack. After executing the start() method, the thread changes
the state from New to Runnable. It executes the run() method when the thread gets
the correct time to execute it.

Let's take an example to understand how we can create a Java

thread by extending the Thread class:

ThreadExample1.java
1. // Implementing runnable interface by extending Thread class  
2. public class ThreadExample1 extends Thread {  
3.      // run() method to perform action for thread.   
4.      public void run()  
5.      {    
6.         int a= 10;  
7.         int b=12;  
8.         int result = a+b;  
9.         System.out.println("Thread started running..");  
10.         System.out.println("Sum of two numbers is: "+ result);  
11.      }  
12.      public static void main( String args[] )  
13.      {  
14.       // Creating instance of the class extend Thread class  
15.         ThreadExample1 t1 = new  ThreadExample1();  
16.         //calling start method to execute the run() method of the Thread class  
17.         t1.start();  
18.      }  
19. }  

Output:

Creating thread by implementing the runnable


interface :
public class RunnableDemo {
 
    public static void main(String[] args)
    {
        System.out.println("Main thread is- "
                        + Thread.currentThread().getName());
        Thread t1 = new Thread(new RunnableDemo().new RunnableImpl());
        t1.start();
    }
 
    private class RunnableImpl implements Runnable {
 
        public void run()
        {
            System.out.println(Thread.currentThread().getName()
                             + ", executing run() method!");
        }
    }
}

Output:
Main thread is- main
Thread-0, executing run() method!

Priority of a Thread (Thread Priority)


Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, the thread scheduler schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on
JVM specification that which scheduling it chooses. Note that not only JVM a Java
programmer can also assign the priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority


Let's discuss the setter and getter method of the thread priority.
public final int getPriority(): The java.lang.Thread.getPriority() method returns the
priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority()


method updates or assign the priority of the thread to newPriority. The method
throws IllegalArgumentException if the value newPriority goes out of the range,
which is 1 (minimum) to 10 (maximum).

49M
889
Java Try Catch

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1


and the value of MAX_PRIORITY is 10.
Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to
any shared resource.

Java Synchronization is better option where we want to allow only one thread to
access the shared resource.

Why use Synchronization?


The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization Hello Java Program for Beginners

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive.
2. Cooperation (Inter-thread communication in java)

3. Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every
object has a lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them,
and then release the lock when it's done with them.

Java Synchronized Method


If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.
Inter-thread Communication in Java
Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is


paused running in its critical section and another thread is allowed to enter (or lock)
in the same critical section to be executed.It is implemented by following methods
of Object class:
o wait()
o notify()
o notifyAll()

1) wait() method
The wait() method causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to be awakened. The
choice is arbitrary and occurs at the discretion of the implementation.

Syntax:

public final void notify()  

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()  

You might also like