Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
99 views

IT Unit 6 - Multi Threaded Programming and Exception Handling-1

The document discusses multi-threaded programming and exception handling in Java. It covers key concepts like the thread model in Java, thread priorities, synchronization, implementing threads using the Thread class and Runnable interface, creating multiple threads, thread methods like join(), alive(), suspend(), resume(), inter-thread communication, deadlocks, sources of errors, advantages of exception handling, dealing with exceptions, and exception types. It provides examples of multithreading in applications and real life.

Uploaded by

shiva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

IT Unit 6 - Multi Threaded Programming and Exception Handling-1

The document discusses multi-threaded programming and exception handling in Java. It covers key concepts like the thread model in Java, thread priorities, synchronization, implementing threads using the Thread class and Runnable interface, creating multiple threads, thread methods like join(), alive(), suspend(), resume(), inter-thread communication, deadlocks, sources of errors, advantages of exception handling, dealing with exceptions, and exception types. It provides examples of multithreading in applications and real life.

Uploaded by

shiva
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Unit 6 - Multi threaded programming

and Exception handling

By,
Asmatullah Khan,
CL/CP, GIOE,
Secunderabad.
Contents
1. Explain the thread model of Java.
2. Explain thread priorities.
3. Explain the concept of synchronization.
4. Implement the thread class and runnable interface.
5. Illustrate the creation of a thread
6. Illustrate the creation of multiple threads.
7. Describe alive( ), join ( ), suspend( ), resume( ) methods.
8. Explain Inter thread communication.
9. Explain dead lock.
10. Explain the sources of errors.
11. Write the advantages of Exception handling.
12. Explain how to deal with exceptions.
13. Explain the types of Exceptions
14. Explain the concept of Multi-catch statements programs.
A thread is a basic execution unit which has its own
program counter, set of the register, stack but it shares
the code, data, and file of the process to which it belongs.

Threads exist within a process –every process has at least one.


Threads share the process’s resources including
memory and open files. This makes for efficient but
potentially problematic communication.
MultiTasking
Processor based MultiTasking Thread based MultiTasking

• It allows processes(programs) • It allows part of the same


to run concurrently program to run concurrently,
• Ex: Notepad, Media Player, and means single process, having
Games can run concurrently on multiple paths of execution –
Computer called Multithreading

MultiTasking

Processor Based Thread Based


MultiTasking MultiTasking
Multithreading in reality
• The process of executing multiple threads simultaneously is
known as multithreading.

• Example of Multithreading in real life usage


▫ Games are very good examples of threading. You can use multiple
objects in games like cars, motor bikes, animals, people etc. All
these objects are nothing but just threads that run your game
application.
▫ In word processor one thread take the input from keyboard and
another thread check the spelling mistakes and third thread count
the words.
▫ Railway ticket reservation system where multiple customers
accessing the server.
▫ Multiple account holders accessing their accounts simultaneously
on the server. When you insert a ATM card, it starts a thread for
performing your operations.
Multithreading in practicality
Advantages of Multithreading Disadvantage of Multithreading
• The main advantage is proper • Complex debugging and
utilization or max utilization is testing processes.
possible. • Increased difficulty level in
• Decreased cost of maintenance. writing a program.
• Time saving. • Unpredictable results.
• Improves the performance of
complex applications.
• Parallelize tasks.
Introduction to Process and Threads
• What is a Process? • What is a Thread?
▫ An executing instance of a program is called ▫ A Thread is a single sequential flow of execution
process. within a program.
▫ A Thread is a subset of process.
▫ Its also known as “Heavyweight process”.
▫ Thread is considered as “Light Weight Process”
▫ Each process have process ID, separate memory because it use less resource than process.
space. ▫ They share the address space of the process but
▫ Its difficult to create a process as that’s a task of process have their own address space.
OS. ▫ Its easy to create a thread using Java, which is the first
language to introduce and adapt threading concept.
▫ Every thread in a Java created and controlled by a
▫ For example while writing java program in unique object of the class.
editor we can run MP3 player. At the same time java.lang.Threadclass
we can download file from net. All these task are
executing simultaneously and independent of ▫ For example, playing a video on the same webpage
each other. while allowing user to use video controls and also
commenting options.
Thread model of Java
• In Java, the word thread means two different things.
▫ An instance of Thread class.
 An instance of Thread class is just an object, like any other object in
java.
▫ or, A thread of execution.
 But a thread of execution means an individual "lightweight" process
that has its own call stack.

• A thread is a:
▫ Facility to allow multiple activities within a single process
▫ Referred as lightweight process
▫ A thread is a series of executed statements
▫ Each thread has its own program counter, stack and local
variables
▫ A thread is a nested sequence of method calls
▫ It shares memory, files and per-process state
Thread model of Java cont…
• Every Java Program has a default main thread.
▫ A thread is an independent path of code execution.
• Many threads can run concurrently in a Java Program.
• Threads can be used to perform time-intensive tasks and run them in the background.
▫ This allows the application to remain responsive to its users.
• Each thread executes runnable object.
▫ Runnables are objects that encapsulate code sequences.
• Threads can initiate an asynchronous task.
▫ Asynchronous indicates that it can run concurrently [at the same time instead of
sequentially]
• The JVM gives each thread its own private JVM stack.
▫ This prevents threads from interfering with each other.

• Java supports threads through


▫ Java.lang.ThreadClass
▫ java.lang.Runnableinterface

• Threads are either daemon or non-daemon.


▫ Daemon threads don’t stop the JVM from ending.
 Java garbage Collection runs on daemon thread.
▫ Threads by default are non-daemon threads.
 The main thread is non-daemon thread.
Involvement of JVM and Thread in Java Applications
• When we execute an application:
1. The JVM creates a Thread object whose task is defined by the
main() method.
2. The JVM starts the thread.
3. The thread executes the statements of the program one by one.
4. After executing all the statements, the method returns and the
thread dies.
Thread model of Java – main thread
• When a Java program starts up, class MainThread
one thread begins running {
immediately, usually called the public static void main(String[] args)
main thread of your program, {
because it is the one that is Thread t=Thread.currentThread();
executed when your program t.setName("MainThread");
begins.
System.out.println("Name of thread is "+t);
}
• Although the main thread is
}
automatically created, you can
control it by obtaining a reference
to it by calling currentThread() Output:
method. Name of thread is Thread[MainThread,5,main]

• Two important things to know


about main thread are,
1. It is the thread from which other
threads will be produced.
2. main thread must be always the
last thread to finish execution.
Thread model of Java – thread lifecycle
• During the life time of a thread, there are many states it can enter. They include:
1. Newborn state
2. Runnable State
3. Running State
4. Blocked State
5. Dead State State diagram of a Thread

New
Thread

Active
Thread

Idle Thread
(Not Runnable)
Thread Lifecycle – Newborn State
• When we create a thread object, the thread is born and is said to be in newborn state.
• The thread is not yet scheduled for running. At this state, we can do only one of the
following with it:
1. Schedule it for running using start() method.
2. Kill it using stop() method.
State diagram of a Thread

New
Thread

Active
Thread

Idle Thread
(Not Runnable)
Thread Lifecycle – Runnable state (start())
• The runnable state means that the thread is ready for execution and is waiting for the availability of
the processor.
• That is, the thread has joined the queue of threads that are waiting for execution.
• If all threads have equal priority, then they are given time slots for execution in round robin fashion.
i.e. firstcome, first-serve manner.

State diagram of a Thread

New
Thread

Active
Thread

Idle Thread
(Not Runnable)
Thread Lifecycle – Running state
• Running means that the processor has given its time to the thread for its
execution.
• The thread runs until it relinquishes control on its own or it is preempted by
a higher priority thread.
State diagram of a Thread

New
Thread

Active
Thread

Idle Thread
(Not Runnable)
Thread Lifecycle – Blocked state
• A thread is said to be blocked when it is prevented form entering into the runnable state and
subsequently the running state.
• This happens when the thread is sleeping, or waiting in order to satisfy certain requirements.
• A blocked thread is considered “ not runnable” but not dead and therefore fully qualified to run again.

State diagram of a Thread

New
Thread

Active
Thread

Idle Thread
(Not Runnable)
Thread Lifecycle – Dead state
• A running thread ends its life when is has completed executing its run() method. It is a natural death.
• However, we can kill it by sending the stop message to it at any state thus causing a premature death
to it.
• A thread can be killed as soon it is born, or while it is running, or even when it is in “not runnable”
(blocked) condition.

State diagram of a Thread

New
Thread

Active
Thread

Idle Thread
(Not Runnable)
Thread Creation or Declaration of User-Defined Threads
• Thread can be declared in two ways :
1. Create a class that extends the Thread class
2. Create a class that implements the Runnable interface

1. Create a class by extending Thread 1. Create a class that implements the interface
class and override run() method: Runnable and override run() method:

class MyThread extends Thread class MyThread implements Runnable


{ {
public void run() public void run()
{ {
// thread body of execution // thread body of execution
} }
} }

2. Creating Object:
2. Create object: MyThread myObject = new MyThread();
MyThread thr1 = new MyThread(); 3. Creating Thread Object:
3. Start Execution of threads: Thread thr1 = new Thread( myObject );
thr1.start(); 4. Start Execution:
thr1.start();
Program to create a Thread – Using extends for
java.lang.Thread class
class Demo
class MyThread extends Thread
{
{
public static void main(String args[])
public void run()
{
{ //Job of thread executed by child thread //main thread creating child thread object
for(int i=0;i<10;i++) MyThread t=new MyThread();
{ //starting of thread
System.out.println(“child thread”); t.start();
} //Now there are two threads – main and child thread
}
} for(int i=0;i<10;i++)
{//Job of thread executed by main thread
System.out.println("main thread");
}
}
}
Compile and Check for sequence of
execution of child and main thread jobs
Program to create a Thread – Using implements
for java.lang.Runnable interface
class Demo
class MyThread1 implements Runnable
{
{
public static void main(String args[])
public void run()
{
{//Job of thread executed by child thread
//main thread creating child thread object
for(int i=0;i<5;i++)
MyThread1 t1=new MyThread1();
{
Thread obj1=new Thread(t1);
System.out.println("child thread "+i);
//starting of thread
}
obj1.start();
} //Now there are two threads – main and child thread
}
for(int i=0;i<5;i++)
{//Job of thread executed by main thread
System.out.println(“main thread "+i);
}
}
Compile and Check for sequence of }
execution of child and main thread jobs
Difference between extends Thread class and implements Runnable
• The limitation with "extends Thread" approach is that if you extend Thread, you
can not extend anything else. Java does not support multiple inheritance. In
reality, you do not need Thread class behavior, because in order to use a thread
you need to instantiate one anyway.

• On the other hand, Implementing the Runnable interface gives you the choice to
extend any class you like, but still define behavior that will be run by separate
thread.

• Another difference between Thread and Runnable comes from the fact that you
are extending Thread class just for run() method but you will get overhead of all
other methods which come from Thread class. So, if your goal is to just write
some code in run() method for parallel execution then use Runnable instead of
extending Thread class.

• When you extends Thread class, each of your thread creates unique object and
associate with it.

• When you implements Runnable, it shares the same object to multiple


threads.

• When you implements Runnable, you can save a space for your class to extend
any other class in future or now.
Thread Methods - predefined
• currentThread() - This method return complete information about the
current thread like it return name of current thread, name of group of
current thread, priority number of current thread.
• start()
• run()
• stop()
• getName() - It is a sub method of current thread method and it return
name of current thread.
• setName() - It is a child method of current thread method and it is use to
set name of current thread.
• sleep() - This method is used to block the current thread until the given
sleep time is not complete.
• getpriority() - It is a child method of current thread and this method
return the priority number of the current thread.
• setpriority() - It is a child method of current thread method and this
method is used to set the priority number of current thread.
• wait()
• join()
• isAlive()
Thread methods – currentThread()
class Demo
{
public static void main(String args[])
{
System.out.println("current thread information is");
System.out.println(Thread.currentThread());
}
}
Thread methods – getName()
class Demo
{
public static void main(String args[])
{
System.out.println("name of current thread ");
System.out.println(Thread.currentThread().getName());
}
}
output
name of current thread
main
Thread methods – setName()
class Demo
{
public static void main(String args[])
{
Thread.currentThread().setName("Parent");
System.out.println("name of current thread ");
System.out.println(Thread.currentThread().getName());
}
} output
name of current thread
Parent
Thread methods – getPriority()
class Demo
{
public static void main(String args[])
{
System.out.println("current thread priority ");
System.out.println(Thread.currentThread().getPriority());
}
}
Output
current thread priority
5
Thread methods – setPriority()
class Demo
{
public static void main(String args[])
{
Thread.currentThread().setPriority(9);
System.out.println("current thread priority ");
System.out.println(Thread.currentThread().getPriority());
}
} Output
current thread priority
9
Thread methods – sleep()
class Demo
{
public static void main(String args[])
{
int i;

for(i=1;i<=5;i++)
{
System.out.println(i);
try Output
{ 1
Thread.sleep(2000); //2 sec// 2
} 3
catch(Exception e) 4
{ 5
}
}
}
}
Thread methods – stop()
class Thread1 extends Thread class Thread2 extends Thread class Demo
{ { {
public void run() public void run() public static void
{ { main(String args[])
for(int i=0;i<5;i++) for(int j=0;j<5;j++) {
Thread1 t1=new Thread1();
{ { Thread2 t2=new Thread2();
if(i==2) if(j==3) t1.start();
stop(); stop(); t2.start();
System.out.println("Thread1:"+i); System.out.println("Thread 2:"+j);
}
} }
} } }
} }

output
Thread 1:0
Thread 1:1
Thread 2:0
Thread 2:1
Thread 2:2
Thread methods – yield()
yield() method causes to pause current executing thread for giving a chance to remaining
waiting threads of same priority.
If there are no waiting threads or all waiting threads have low priority then the same thread will
continue its execution once again.

class Thread1 extends Thread class Thread2 extends Thread class Demo
{ { {
public void run() public void run() public static void
{ { main(String args[])
for(int i=0;i<5;i++) for(int j=0;j<5;j++) {
Thread1 t1=new Thread1();
{ { Thread2 t2=new Thread2();
if(i==2) if(j==3) t1.start();
yield(); yield(); t2.start();
System.out.println("Thread1:"+i); System.out.println("Thread 2:"+j);
}
} } Output
Thread 1:0
System.out.println("Exit from System.out.println("Exit from } Thread 1:1
thread1"); thread2"); Thread 2:0
Thread 2:1
} } Thread 2:2
Thread 2:3
Thread 2:4
} } Exit from thread2
Thread 1:2
Thread 1:3
Thread 1:4
Exit from thread1
Thread methods – isAlive()
isAlive() method tests if the thread is alive or not and it return boolean value.

class MyThread extends Thread class Demo


{ {
public void run() public static void main(String args[])
{ {
for(int i=0;i<5;i++) MyThread t1=new MyThread();
{ t1.start();
System.out.println("status :"+isAlive()); System.out.println("new status :"+t1.isAlive());
} }
}
}
}

output
new status :true
status :true
status :true
status :true
status :true
status :true
Thread methods – join() output
MyThread :0
If a thread wants to wait until completing some other thread then we MyThread :1
should go for join MyThread :2
MyThread :3
method. For example, if a thread t1 wants to wait until completing t2 MyThread :4
then “t1 has to call t2.join()”. Exit from my thread
Main Thread :0
If t1 executes t2.join() then immediately t1 will enter into waiting Main Thread :1
state until t2 completes. Once t2 completes then t1 will continue its Main Thread :2
Main Thread :3
execution. class Demo Main Thread :4
Exit from main thread
{
public static void main(String args[])
class MyThread extends Thread {
{ MyThread t1=new MyThread();
public void run() t1.start();
{ for(int j=0;j<5;j++)
for(int i=0;i<5;i++) {
{ try { t1.join(); }
System.out.println("MyThread :"+i); catch(Exception e) { }
} }
System.out.println("Exit from my System.out.println("Exit from main thread");
thread");
}
}
} }
Thread methods – synchronized(this)
• Synchronization in java is the capability of 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 we use :
1. To prevent thread interference.
2. To prevent consistency problem.

• Synchronized method is used to lock an object for any


shared resource.
Thread methods – without using synchronized()
output
t1:0
t1:1
t2:0
t1:2
t2:1
t1:3
t2:2
class Demo
t1:4 {
t2:3
t2:4
public static void main(String args[])
class B extends Thread {
{ B b=new B();
public void run() Thread t1=new Thread(b);
{ t1.setName("t1:");
for(int i=0;i<5;i++) t1.start();
{ Thread t2=new Thread(b);
System.out.println(Thread.currentThread().getName()+(i));
t2.setName("t2:");
}
t2.start();
}
}
}
}
Thread methods – without using synchronized()
output
t1:0
t1:1
t1:2
t1:3
t1:4
t2:0
t2:1
class Demo
t2:2 {
class B extends Thread t2:3
t2:4
public static void main(String args[])
{ {
public void run() B b=new B();
{ Thread t1=new Thread(b);
Synchronized(this) t1.setName("t1:");
{ t1.start();
for(int i=0;i<5;i++) Thread t2=new Thread(b);
{ t2.setName("t2:");
System.out.println(Thread.currentThread().getName()+(i)); t2.start();
} }
}
} }
}
Thread related Object class methods –
wait(), notify(), notifyAll()
• Two thread communicate each other using wait(), notify() and notifyAll()
methods.

• wait(), notify() and notifyAll() method are present in object class but not in
thread class.

• wait(), notify() and notifyAll() method are called from synchronized area
otherwise we get run time exception error saying “illegal moniter state
exception”

• If a thread called wait() method, it immediately enters in waiting state; but in


case of notify() method it does not immediately enter in waiting state.

• wait(), notify() and notifyAll() methods are only method which release the lock.

• Note:
▫ Every wait method throws interrupted exception which is checked exception hence
whenever we are using wait method compulsory we should handle these interrupted
exception either by try, catch or by throws keyword otherwise we will get compile time
error
Difference between notify() and notifyAll()
• We can use notify() method to give notification for only
one waiting thread if multiple threads are waiting then
only one thread will be notify and remaining thread will
have to wait for further notification.

• Which thread will be notify we can’t predict it depend on


JVM.

• We can use notifyAll() to give the notification for all


waiting threads of a particular object even though
multiple thread notify but execution will be perfored one
by one because threads wii require lock and only one
lock is available
output
main thread trying to call wait method

Thread related Object class


child thread starts calculation
child thread try to give notification
main thread got notification

methods – wait(), notify() 5050

class ThreadB extends Thread


{
class ThreadA int total=0;
{ public void run()
public static void main(String args[]) throws {
Exception synchronized(this)
{ {
ThreadB b=new ThreadB(); System.out.println("child thread
b.start(); starts calculation"); //2
synchronized(b) for(int i=1;i<=100;i++)
{ {
System.out.println("main thread trying to total=total+i;
call wait method"); //1 }
b.wait(); System.out.println("child thread try
System.out.println("main thread got to give notification"); //3
notification"); //4 this.notify();
System.out.println(b.total); //5 }
} }
}
} }
Summary for Thread model of Java –
life cycle of thread revisited
Object.notify(), or
Object.notifyAll()
Waiting

Object.notify(), or
Object.notifyAll()
Sleeping
Object.wait()

Ready-to-run
start()

stop(), Running
or run()
exits
Data
received or
Dead Lock
obtained

Blocked
Differences between Process and Thread
Process Thread
• Process can be divided into • Threads cannot be sub
multiple threads divided.
• Each process has its own • Threads of the same process
memory space share a common memory
• It is difficult to create a space.
process • It is easy to create a thread
Producer consumer problem
• Producer thread is responsible to produce items to the queue and consumer
thread is responsible is responsible to consume items to the queue.
• If queue is empty then consumer thread will call wait method and enter into
waiting state.
• After producing items to the queue producer thread is responsible to call notify
method then waiting consumer will get notification and continue its execution
with updated items.

class ConsumerThread class ProducerThread


{ {
consume() Produce()
{ {
synchronized(q) synchronized(q)
{ {
if(q is empty) produce items to the queue
q.wait(); q.notify();
else }
consume items }
} }
}
}
An exception is an abnormal condition which occurs
during run time and disrupts the normal flow of the
program. This exception must be handled to maintain the
normal flow of the program.

If exception is not handled properly, the rest of the


program will not be executed. Hence, causing the abrupt
termination of the program. Therefore, you must handle
the exceptions for the smooth flow of the program.

To handle the run time exceptions, one mechanism is


provided in java and it is called exception handling. Java
provides a robust and object oriented way to handle
exception scenarios, known as Java Exception
Handling.

Note: Java Exception handling is a framework that is


used to handle runtime errors only, compile time errors
are not handled by exception handling in java.
Exception Handling Overview
• An exception is a problem that arises during the
execution of a program.

• An exception can occur for many different reasons,


including the following:
▫ A user has entered invalid data.
▫ A file that needs to be opened cannot be found.
▫ A network connection has been lost in the middle of
communications or the JVM has run out of memory.

• Some of these exceptions are caused by user error,


others by programmer error, and others by physical
resources that have failed in some manner.
Exception-Handling Overview 1 of 4
public class Quotient {
public static void main(String[] args) { 1. Naive code
Scanner input = new Scanner(System.in); No protection
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();

System.out.println(number1 + " / " + number2 + " is " +


(number1 / number2));
}
}

CONSOLE

Enter two integers: 100 0


Exception in thread "main" java.lang.ArithmeticException: / by zero
at Quotient.main(Quotient.java:15)

RED text messages are runtime ERRORS caught by the JVM


Exception-Handling Overview 2 of 4
public class QuotientWithIf { 2. Protect code
public static void main(String[] args) { with if-stm
Scanner input = new Scanner(System.in);

// Prompt the user to enter two integers


System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();

if (number2 != 0)
System.out.println(number1 + " / " + number2 + " is " +
(number1 / number2));
else
System.out.println("Divisor cannot be zero ");
}
}

CONSOLE

Enter two integers: 100 0


Divisor cannot be zero
Exception-Handling Overview 3 of 4
public class QuotientWithException {
public static void main(String[] args) { 3. Protect code
Scanner input = new Scanner(System.in);
with Exception
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();

try {
double result = number1 / number2;

System.out.println( number1 + " / " + number2 + " is " + result );

}
catch (Exception ex) {
System.out.println( "Exception: an integer cannot be divided by zero ");
}

System.out.println("Execution continues ...");


}
}

CONSOLE
Enter two integers: 100 0
Exception: an integer cannot be divided by zero
Execution continues ...
Exception Handling Advantages
Exception handling separates error-handling code from normal programming
tasks, consequently making programs easier to read and to modify.

Business logic
(this is what needs to be done)

Deal with troubles here


Exception Handling Overview 4 of 4
public class QuotientWithException {

public static void main(String[] args) { 4. Throwing and


Scanner input = new Scanner(System.in); catching a ‘local’
// Prompt the user to enter two integers exception
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();

try {
if (number2 == 0) Your turn
throw new ArithmeticException("Divisor cannot be zero"); 1. Replace with
Exception(…)
System.out.println(number1 + " / " + number2 + " is " + 2. What if the try-
(number1 / number2)); catch statement
} is not used?
catch (Exception ex) { 3. Use
System.out.println( "Exception: an integer " + ex.getMessage()
"cannot be divided by zero ");
}
System.out.println("Execution continues ...");
} CONSOLE
} Enter two integers: 100 0
Exception: an integer cannot be divided by zero
Execution continues ...
Java Exception Handling
• Java developers have identified most possible situations that are capable of
terminating a program abruptly and represented them as a hierarchy of classes
handled by java.lang.Throwble.

• Java being an object oriented programming language, whenever an error occurs


while executing a statement, creates an exception object and then the normal
flow of the program halts and JRE tries to find someone that can handle the raised
exception.
▫ The exception object contains a lot of debugging information such as method hierarchy,
line number where the exception occurred, type of exception etc.

• When the exception occurs in a method, the process of creating the exception
object and handing it over to runtime environment is called “throwing the
exception”.

• Once runtime receives the exception object, it tries to find the handler for the
exception. Exception Handler is the block of code that can process the exception
object.

• The logic to find the exception handler is simple – starting the search in the
method where error occurred, if no appropriate handler found, then move to the
caller method and so on.
Exception Handling Overview – two categories of Exceptions
Property Checked Exception Unchecked Exception
Also known as checked exceptions are known to unchecked exceptions are not known
compiler i.e they are the exceptions to compiler. They are the exceptions
that are checked at compile time and that are not checked at compile time,
are known as compileTime because they occur only at run time.
exceptions in java. That’s why these exceptions are also
known as runtime exceptions in java.
Should be solved Checked exceptions are those which Unchecked exceptions are those which
at compile or need to be taken care at compile need to be taken care at runtime in java.
runtime? time in java.
Benefit/ We cannot proceed until we fix Whenever runtime exception occurs
Advantage compilation issues which are most execution of program is interrupted, but
likely to happen in program, this by handling these kind of exception we
helps us in avoiding runtime avoid such interruptions and end up
problems upto lot of extent in java. giving some meaningful message to
user in java.
Exception For propagating checked unchecked exceptions are
propagation exceptions method must throw automatically propagated in java.
exception by using throws keyword.
Most frequently faced SQLException, NullPointerException,
exceptions IOException, ArithmeticException ArrayIndexOutOfBoundsException.
ClassNotFoundException
Java Exception Handling – Class Hierarchy of Exceptions

• All exception classes are subtypes of the java.lang.Exception class.

• The exception class is a subclass of the Throwable class.

• Other than the Exception class there is another subclass called


Error which is derived from the Throwable class.

• Errors are not normally trapped form the Java programs.


▫ These conditions normally happen in case of severe failures, which
are not handled by the java programs. Errors are generated to
indicate errors-messages generated by the runtime environment.
 Example : JVM is out of Memory. Normally programs cannot recover
from errors.

• The Exception class has two main subclasses:


▫ IOException class and
▫ RuntimeException Class.
Java Exception Handling – Class Hierarchy of Exceptions
Java Exception Handling –
Class Hierarchy of Exceptions
Java Exception Handling Keywords
• throw
▫ We know that if any exception occurs, an exception object is getting created and then
Java runtime starts processing to handle them.
▫ Sometime we might want to generate exception explicitly in our code, for example in a
user authentication program we should throw exception to client if the password is null.
▫ throw keyword is used to throw exception to the runtime to handle it.
• throws
▫ When we are throwing any exception in a method and not handling it, then we need to
use throws keyword in method signature to let caller program know the exceptions that
might be thrown by the method.
▫ The caller method might handle these exceptions or propagate it to it’s caller method
using throws keyword.
▫ We can provide multiple exceptions in the throws clause and it can be used with main()
method also.
• try-catch
▫ We use try-catch block for exception handling in our code.
▫ try is the start of the block and catch is at the end of try block to handle the exceptions.
▫ We can have multiple catch blocks with a try and try-catch block can be nested also.
▫ catch block requires a parameter that should be of type Exception.
• finally
▫ finally block is optional and can be used only with try-catch block.
▫ Since exception halts the process of execution, we might have some resources open that
will not get closed, so we can use finally block.
▫ finally block gets executed always, whether exception occurred or not.
Java Exception Handling Keywords – try block
• The functionality of try keyword is to identify an exception object.

• And catch that exception object and transfer the control along with
the identified exception object to the catch block by suspending the
execution of the try block.

• All the statements which are proven to generate exceptions should


be place in try block.

• Syntax of try block:


try
{
//try block
//keep those statements which may
//throw run time exceptions
}
Java Exception Handling Keywords – catch block
• The functionality of catch block is to receive the exception class
object that has been send by the "try". And catch that exception
class object and assigns that exception class object to the reference
of the corresponding exception class defined in the catch block.

• And handle the exception that has been identified by "try".

• "try" block identifies an exception and catch block handles the


identified exception.

• Syntax of catch block:


catch(Exception e)
{
//catch block.
//one argument of type java.lang.Exception
//catches the exceptions thrown by try block
}
Java Exception Handling Keywords – finally block

• finally blocks are the blocks which are going to get


executed compulsorily irrespective of exceptions.

• finally blocks are optional blocks.

• Syntax of finally block:

finally
{
//This is the finally block.
}
Java Exception Handling Throwable class - Methods with Description
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.
Java Exception Handling Keywords – try, catch, finally block example 1
public class ExceptionHandling
{
public static void main(String[] args)
{
String[] s = {"abc", "123", "xyz", "456"}; //String Array containing valid and invalid numeric values

for (int i = 0; i < s.length; i++)


{
try
{
int intValue = Integer.parseInt(s[i]); //This statement may throw NumberFormatException
}
catch(NumberFormatException ex)
{
System.out.println("The thrown NumberFormatException will be caught here");
}
finally
{ Output
System.out.println("This block is always executed");
} The thrown NumberFormatException will be caught here
This block is always executed
} This block is always executed
} The thrown NumberFormatException will be caught here
This block is always executed
} This block is always executed
Java Exception Handling Keywords – try, catch, finally block example 2

public class ExceptionHandling Note: When a statement throws an


{ exception in the try block, the remaining
public static void main(String[] args) part of the try block will not be executed.
{ Program control comes out of the try block
try and enters directly into catch block.
{
int i = 10/0; //This statement throws ArithmeticException

System.out.println("This statement will not be executed");


}
catch(Exception ex)
{
System.out.println("This block is executed immediately after an exception is thrown");
}
finally
{
System.out.println("This block is always executed");
}
}
Output

} This block is executed immediately after an exception is thrown


This block is always executed
Java Exception Handling Keywords – try, catch, finally block example 3
public class ExceptionHandling Note: try, catch and finally blocks form one
{ unit. i.e You can’t keep other statements in
public static void main(String[] args)
{ between try, catch and finally blocks.
System.out.println("You can keep any number of statements here");

try
{
int i = 10/0; //This statement throws ArithmeticException

System.out.println("This statement will not be executed"); Output


}
You can keep any number of statements here
This block is executed immediately after an exception is thrown
//You can't keep statements here This block is always executed
You can keep any number of statements here
catch(ArithmeticException ex)
{ System.out.println("This block is executed immediately after an exception is thrown"); }

//You can't keep statements here

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

System.out.println("You can keep any number of statements here");


}
}
Java Exception Handling Keywords – try, catch, finally block example 4
public class ExceptionHandling
Note: You can display the description of an
{
public static void main(String[] args)
exception thrown using Exception object in
{ the catch block.
try
{
String s = null;

System.out.println(s.length()); //This statement throws NullPointerException

System.out.println("This statement will not be executed");


}
catch(Exception ex)
{
System.out.println(ex); //Output : java.lang.NullPointerException

ex.printStackTrace(); //This prints stack trace of exception


}
finally
{ System.out.println("This block is always executed"); }
} Output
} java.lang.NullPointerException
java.lang.NullPointerException at ExceptionHandling.main(ExceptionHandling.java:9)
This block is always executed
Java Exception Handling – multi catch blocks
• In some cases, A single statement may throw more than
one type of exception.

• In such cases, Java allows you to put more than one


catch blocks.

• One catch block handles one type of exception.

• When an exception is thrown by the try block, all the


catch blocks are examined in the order they appear and
one catch block which matches with exception thrown
will be executed.

• After, executing catch block, program control comes out


of try-catch unit.
Java Exception Handling Keywords – try, catch, finally block example 4
public class ExceptionHandling
{ Note: Check Notes Section for
public static void main(String[] args) explanation and output
{
String[] s = {"abc", "123", null, "xyz"}; //String array containing one null object
Output
NumberFormatException will be caught here

for (int i = 0; i < 6; i++) After executing respective catch block, this statement will
After executing respective catch block, this statement will
be executed
be executed

{
NullPointerException will be caught here
After executing respective catch block, this statement will be executed
NumberFormatException will be caught here

try { After executing respective catch block, this statement will


ArrayIndexOutOfBoundsException will be caught here
After executing respective catch block, this statement will
be executed

be executed

int a = s[i].length() + Integer.parseInt(s[i]); ArrayIndexOutOfBoundsException will be caught here


After executing respective catch block, this statement will be executed

//This statement may throw NumberFormatException, NullPointerException and ArrayIndexOutOfBoundsException


}

catch(NumberFormatException ex)
{ System.out.println("NumberFormatException will be caught here"); }

catch (ArrayIndexOutOfBoundsException ex)


{ System.out.println("ArrayIndexOutOfBoundsException will be caught here"); }

catch (NullPointerException ex)


{ System.out.println("NullPointerException will be caught here"); }

System.out.println("After executing respective catch block, this statement will be executed");


}
}
}
Java Exception Handling Keywords – try, catch, finally block example 5
Note: From Java 7 onward, there is one more way for
public class ExceptionHandling handling multiple exceptions. Multiple exceptions
{
thrown by the try block can be handled by a single
public static void main(String[] args)
{ catch block using pipe (|) operator.
String[] s = {"abc", "123", null, "xyz"}; //String array containing one null object

for (int i = 0; i < 6; i++)


{
try
{
int a = s[i].length() + Integer.parseInt(s[i]);

//This statement may throw NumberFormatException, NullPointerException and


ArrayIndexOutOfBoundsException
}

catch(NumberFormatException | NullPointerException | ArrayIndexOutOfBoundsException ex)


{
System.out.println("Now, this block handles NumberFormatException, NullPointerException and
ArrayIndexOutOfBoundsException");
}
} Output
Now, this block handles NumberFormatException, NullPointerException and ArrayIndexOutOfBoundsException
} Now, this block handles NumberFormatException, NullPointerException and ArrayIndexOutOfBoundsException
Now, this block handles NumberFormatException, NullPointerException and ArrayIndexOutOfBoundsException
} Now, this block handles NumberFormatException, NullPointerException and ArrayIndexOutOfBoundsException
Now, this block handles NumberFormatException, NullPointerException and ArrayIndexOutOfBoundsException
Java Exception Handling Keywords – try, catch, finally block example 6
public class ExceptionHandling
Note: Check notes section for explanation.
{
public static void main(String[] args)
{
String[] s = {"abc", "123", null, "xyz"}; //String array containing one null object

for (int i = 0; i < 6; i++)


{
try
{
int a = s[i].length() + Integer.parseInt(s[i]);

//This statement may throw NumberFormatException, NullPointerException and ArrayIndexOutOfBoundsException


}

catch(Exception ex)
{
System.out.println("This block handles all types of exceptions");
}
}
} Output
This block handles all types of exceptions
This block handles all types of exceptions
This block handles all types of exceptions
} This block handles all types of exceptions
This block handles all types of exceptions
Java Exception Handling Keywords – try, catch, finally block example 7
Note: The order of catch blocks should be from most
public class ExceptionHandling specific to most general ones. i.e Sub classes of
{ Exception must come first and super classes later. If
you keep the super classes first and sub classes later,
public static void main(String[] args)
you will get compile time error : Unreachable Catch
{ Block.
try
{
int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
}

catch(Exception ex)
{ System.out.println("This block handles all exception types"); }

catch(NumberFormatException ex)
{
//Compile time error
//This block becomes unreachable as
//exception is already handled by above catch block
}
} Output
ExceptionHandling.java:15: error: exception NumberFormatException has already been caught
} catch(NumberFormatException ex)
^
Java Exception Handling Keywords – try, catch, finally block example 8
correct form of ex 7
public class ExceptionHandling Note: The order of catch blocks should be from most
{ specific to most general ones. i.e Sub classes of
public static void main(String[] args) Exception must come first and super classes later. If
{ you keep the super classes first and sub classes later,
try you will get compile time error : Unreachable Catch
{ Block.
int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
}

catch(NumberFormatException ex)
{
System.out.println("This block handles NumberFormatException");
}

catch(Exception ex)
{
System.out.println("This block handles all exception types");
}

catch (Throwable ex)


{
System.out.println("Throwable is super class of Exception");
}
}
Output
} This block handles NumberFormatException
Java Exception Handling Keywords – nested try, catch, finally block example 9
Note: Nested try blocks are useful when different
statements of try block throw different types of
exceptions.
public class ExceptionHandling
{
public static void main(String[] args)
{
String[] s = {"abc", "123", null, "xyz"}; //String array containing one null object

for (int i = 0; i < s.length; i++)


{
try //Outer try block
{
int a = s[i].length(); //This statement may throw NullPointerException

try //Inner try block


{ a = Integer.parseInt(s[i]); //This statement may throw NumberFormatException }
catch (NumberFormatException ex) //Inner catch block
{ System.out.println("NumberFormatException will be caught here"); }
}
catch(NullPointerException ex) //Outer catch block
{ System.out.println("NullPointerException will be caught here"); }
} Output
} NumberFormatException will be caught here
} NullPointerException will be caught here
NumberFormatException will be caught here
Java Exception Handling Keywords – nested try, catch, finally block example 10
public class ExceptionHandling
{ Note: If the exception
public static void main(String[] args) thrown by the inner try block
{
can not be caught by it’s
String[] s = {"abc", "123", null, "xyz"}; //String array containing one null object
catch block, then this
for (int i = 0; i < s.length; i++) exception is propagated to
{ outer try blocks. Any one of
//First Level try-catch block the outer catch block should
try handle this exception
{ otherwise program will
int a = s[i].length(); //This statement may throw NullPointerException
terminate abruptly.
//second level try-catch block
try
{
System.out.println(s[i+1]); //This statement may throw ArrayIndexOutOfBoundsException
//third level try-catch block
try
{ a = Integer.parseInt(s[i]); //This statement may throw NumberFormatException }
catch (NullPointerException e)
{ System.out.println("NumberFormatException will not be caught here"); }
}
catch (NumberFormatException ex)
{ System.out.println("NumberFormatException will be caught here"); }
}
catch(Exception ex)
{ System.out.println("This block catches all types of exceptions"); }
}
} Output
} Check notes section for output
Java Exception Handling Keywords – Return Value From try-catch-finally Blocks example 11

public class ReturnValueFromTryCatchFinally Note: If method returns a value


{ and also has try, catch and finally
public static void main(String[] args) blocks in it, then following two
{ rules need to follow.
System.out.println(methodReturningValue()); //Output : 50 1) If finally block returns a value
then try and catch blocks may or
} may not return a value.
2) If finally block does not return
static int methodReturningValue() a value then both try and catch
{ blocks must return a value.
try finally block overrides any return
{ values from try and catch blocks.
return 10;
}
catch (Exception e)
{
return 20;
}
finally
{
return 50; //This method returns 50 not 10 or 20
}
}
}
Output
50
Throwing and re-throwing an exception
• Throwing an exception:
▫ Throwable class is super class for all types of errors and exceptions. An object to
this Throwable class or it’s sub classes can be created in two ways.
 First one is using an argument of catch block. In this way, Throwable object or
object to it’s sub classes is implicitly created and thrown by java run time system.
 Second one is using new operator. In this way, Throwable object or object to it’s
sub classes is explicitly created and thrown by the code.
▫ An object to Throwable or to it’s sub classes can be explicitly created and
thrown by using throw keyword.
▫ The syntax for using throw keyword is,
throw InstanceOfThrowableType;
where, InstanceOfThrowableType must be an object of type Throwable or subclass of Throwable.

▫ Such explicitly thrown exception must be handled some where in the program,
otherwise program will be terminated.

• Rethrowing an exception:
▫ Exceptions occurred in the try block are caught in catch block. Thus caught
exceptions can be re-thrown using throw keyword.

▫ Re-thrown exception must be handled some where in the program, otherwise


program will terminate abruptly.
Java Exception Handling - throwing exceptions example 12
public class ExceptionHandling Note: It is not compulsory that explicitly
{ thrown exception must be handled by
public static void main(String[] args) immediately following try-catch block. It can be
{ handled by any one of it’s enclosing try-catch
try blocks.
{
methodWithThrow();
}
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException object thrown in methodWithThrow() method will be handled here");
}
}

static void methodWithThrow()


{
try
{
NumberFormatException ex = new NumberFormatException("This is an object of NumberFormatException");

throw ex; //throwing NumberFormatException object explicitly using throw keyword


}
catch(ArithmeticException ex)
{
System.out.println("Explicitly thrown NumberFormatException object will not be caught here");
}
}
} Output
NumberFormatException object thrown in methodWithThrow() method will be handled here
Java Exception Handling - rethrowing exceptions example 13
public class ExceptionHandling
{
Note: We all know that exceptions occurred
in the try block are caught in catch block. Thus
public static void main(String[] args)
caught exceptions can be re-thrown
{
using throw keyword. Re-thrown exception
try
must be handled some where in the program,
{
otherwise program will terminate abruptly.
methodWithThrow();
}
catch(NullPointerException ex)
{
System.out.println("NullPointerException Re-thrown in methodWithThrow() method will be handled here");
}
}

static void methodWithThrow()


{
try
{
String s = null;
System.out.println(s.length()); //This statement throws NullPointerException
}
catch(NullPointerException ex)
{
System.out.println("NullPointerException is caught here");

throw ex; //Re-throwing NullPointerException


} Output
} NullPointerException is caught here
} NullPointerException Re-thrown in methodWithThrow() method will be handled here
Java Exception Handling Keywords- throws
• If a method is capable of throwing an exception that it
could not handle, then it should specify that exception
using throws keyword.

• It helps the callers of that method in handling that


exception.

• The syntax for using throws keyword is,


return_type method_name(parameter_list) throws
exception_list
{
//some statements
}
where, exception_list is the list of exceptions that method may throw.
Exceptions must be separated by commas.
Java Exception Handling - throws keyword example 14
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
methodWithThrows();
}
catch(NullPointerException ex)
{
System.out.println(“NullPointerException thrown by methodWithThrows() method will
be caught here”);
}
}

static void methodWithThrows() throws NullPointerException


{
String s = null;
System.out.println(s.length()); //This statement throws NullPointerException
}

} Output
NullPointerException thrown by methodWithThrows() method will be caught here
Java Exception Handling - throws keyword example 15
public class ExceptionHandling Note: The main use of throws keyword in java is that an exception
can be propagated through method calls.
{
static void methodOne() throws NumberFormatException
{
int i = Integer.parseInt(“abc”); //This statement throws NumberFormatException
}

static void methodTwo() throws NumberFormatException


{ methodOne(); //NumberFormatException is propagated here
}

static void methodThree() throws NumberFormatException


{
methodTwo(); //NumberFormatException is propagated here
}

public static void main(String[] args)


{
try
{ methodThree(); }
catch(NumberFormatException ex)
{ System.out.println(“NumberFormatException will be caught here”); }
}
}
Output
NumberFormatException will be caught here
Java Exception Handling – Propagation of Unchecked Exceptions
Java Exception Handling – Propagation of Checked Exceptions
Packages in java are used to organize related or similar classes,
interfaces and enumerations into one group.

For example,
java.sql package has all classes needed for database operation.
java.io package has classes related to input-output operation.

Packages are also used to avoid naming conflict between the


classes.

Using packages, you can give same name to different classes.


Declaring and Creating Java Packages
• Packages are declared using keyword ‘package’.

• They should be declared in the first statement in a


java file.
▫ If you try to declare packages at any other statements,
you will get compile time error.

package com;
class A
{
//Some statements
}
//package com; If you declare here, it gives compile time error
Conventions for Naming Java Packages
• Only alphabets, numbers and an underscore are allowed
in naming the packages.

• By convention, names of package should start with


lowercase although it is not a condition.

• Package name should start with a alphabets or


underscore but not with a number.
package javaConcept; //Valid package name
package java_Concept; //Valid package name
package java_12; //Valid package name
package 12_java; //Invalid package name, should not start with a number.
package _java12; //Valid package Name
package JAVA; //Valid package name but not recommended.
Compiling and Excuting Java Package Classes
• When you declare a package name in your java file, and package pack1;
after compiling it with -d option, a folder with the same name is class A
created in the specified location and all generated .class files will
be stored in that folder. { //Some statements
}
• You can give same name to more than one classes in different
packages.
package pack2;
class A
• You can compile all the classes in a package at a time like this,
{ //Some statements
>javac pack1/*.java
}
• all the classes in the package pack1 are compiled at a time.
• To run the program, simply call the class which has main method
in it.
>java pack1.MainClass
package pack1.subpack1;
• Packages can have any number of sub packages. While class A
declaring, packages and sub packages are separated by ‘.’ For {
example, //Some Statements
}
• When you compile above example with -d option, generated .class
file is stored in subfolder subpack1 of pack1 folder in the specified
location.
Check Notes Section for –d option and its related usages.

You might also like