23IT1301 - OOPs - Unit - 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Panimalar Engineering College Department of CSE

UNIT - III MULTITHREADING AND EXCEPTION HANDLING 9


Thread-Thread life cycle, creating threads, synchronizing threads, Inter-thread communication,
daemon threads, thread groups - Exceptions - exception hierarchy - throwing and catching
exceptions – built-in exceptions, creating own exceptions, Stack Trace Elements.

3.1: Thread

Definition: Thread
A thread is a lightweight sub-process that defines a separate path of execution. It is the smallest
unit of processing that can run concurrently with the other parts (other threads) of the same
process.

 Threads are independent.


 Exception in one thread, doesn’t affect other threads.
 It uses a shared memory area.

 As shown in the above figure, a thread is executed inside the process.


 There is context-switching between the threads.
 There can be multiple processes inside the OS, and one process can have multiple threads.

1
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
DIFFERENCE BETWEEN THREAD AND PROCESS:

S.NO PROCESS THREAD


1) Process is a heavy weight program Thread is a light weight process
2) Each process has a complete set of its Threads share the same data
own variables
3) Processes must use IPC (Inter-Process Threads can directly communicate with
Communication) to communicate with each other with the help of shared
sibling processes variables
4) Cost of communication between Cost of communication between threads
processes is high. is low.
5) Process switching uses interface in Thread switching does not require
operating system. calling an operating system.
6) Processes are independent of one Threads are dependent of one another
another
7) Each process has its own memory and All threads of a particular process shares
resources the common memory and resources
8) Creating & destroying processes takes Takes less overhead to create and destroy
more overhead individual threads

MULTITHREADING

A program can be divided into a number of small processes. Each small process can be
addressed as a single thread.

Definition: Multithreading
Multithreading is a technique of executing more than one thread, performing different tasks,
simultaneously.
Multithreading enables programs to have more than one execution paths which executes
concurrently. Each such execution path is a thread. For example, one thread is writing
content on a file at the same time another thread is performing spelling check.

Advantages of Threads / Multithreading:


1. Threads are light weight compared to processes.
2. Threads share the same address space and therefore can share both data and code.
3. Context switching between threads is usually less expensive that between processes.
4. Cost of thread communication is low than inter-process communication.
5. Threads allow different tasks to be performed concurrently.
6. Reduces the computation time.
7. Through multithreading, efficient utilization of system resources can be achieved.

2
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
MULTITASKING

Definition: Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to
maximize the utilization of CPU.

Multitasking can be achieved in two ways:


1) Process-based Multitasking (Multiprocessing):-
 It is a feature of executing two or more programs concurrently.
 For example, process-based multitasking enables you to run the Java compiler at the
same time that you are using a text editor or visiting a web site.

2) Thread-based Multitasking (Multithreading):-


 It is a feature that a single program can perform two or more tasks
simultaneously.
 For instance, a text editor can format text at the same time that it is printing, as long as
these two actions are being performed by two separate threads.

Differences between multi-threading and multitasking

Characteristics Multithreading Multitasking


Meaning A process is divided into several The execution of more than one
different sub-processes called as task simultaneously is called as
threads, which has its own path of multitasking.
execution. This concept is called
as multithreading.
Number of CPU Can be one or more than one One
Number of process Various components of the same One by one job is being executed
being executed process are being executed at a at a time.
time.
Number of users Usually one. More than one.
Memory Space Threads are lighter weight. They Processes are heavyweight tasks
share the same address space that require their own separate
address spaces.
Communication Interthread communication is Interprocess communication is
between units inexpensive expensive and limited.
Context Switching Context switching from one Context switching from one
thread to the next is lower in cost. process to another is also costly.

3
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE

3.2: Thread Life Cycle (Different states of a Thread)

Different states, a thread (or applet/servlet) travels from its object creation to object
removal (garbage collection) is known as life cycle of thread. A thread goes through various
stages in its life cycle. At any time, a thread always exists in any one of the following state:
1. New State
2. Runnable State
3. Running State
4. Waiting/Timed Waiting/Blocked state
5. Terminated State/ dead state

1. New State:
A new thread begins its life cycle in the new state. It remains in this state until the program starts
the thread by calling start() method, which places the thread in the runnable state.
 A new thread is also referred to as a born thread.
 When the thread is in this state, only start() and stop() methods can be called. Calling any other
methods causes an IllegalThreadStateException.
 Sample Code: Thread myThread=new Thread();

2. Runnable State:
After a newly born thread is started, the thread becomes runnable or running by calling the run()
method.
 A thread in this state is considered to be executing its task.
 Sample code: myThread.start();
 The start() method creates the system resources necessary to run the thread, schedules the thread
to run and calls the thread’s run() method.

3. Running state:
 Thread scheduler selects thread to go from runnable to running state. In running state Thread
starts executing by entering run() method.
4
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
 Thread scheduler selects thread from the runnable pool on basis of priority, if priority of two
threads is same, threads are scheduled in unpredictable manner. Thread scheduler behaviour is
completely unpredictable.
 When threads are in running state, yield() method can make thread to go in Runnable state.

4. Waiting/Timed Waiting/Blocked State :


 Waiting State:
Sometimes one thread has to undergo in waiting state because another thread starts executing. A
runnable thread can be moved to a waiting state by calling the wait() method.
 A thread transitions back to the runnable state only when another thread signals the waiting
thread to continue executing.
 A call to notify() and notifyAll() may bring the thread from waiting state to runnable state.

 Timed Waiting:
A runnable thread can enter the timed waiting state for a specified interval of time by calling the
sleep() method.
 After the interval gets over, the thread in waiting state enters into the runnable state.
 Sample Code:
try {
Thread.sleep(3*60*1000);// thread sleeps for 3 minutes
}
catch(InterruptedException ex) { }

 Blocked State:
When a particular thread issues an I/O request, then operating system moves the thread to
blocked state until the I/O operations gets completed.
 This can be achieved by calling suspend() method.
 After the I/O completion, the thread is sent back to the runnable state.

5. Terminated State:
A runnable thread enters the terminated state when,
(i) It completes its task (when the run() method has finished)
public void run() { }
(ii) Terminates ( when the stop() is invoked) – myThread.stop();
A terminated thread cannot run again.

New : A thread begins its life cycle in the new state. It remains in this state until the start() method
is called on it.
Runnable : After invocation of start() method on new thread, the thread becomes runnable.
Running : A thread is in running state if the thread scheduler has selected it.
Waiting : A thread is in waiting state if it waits for another thread to perform a task. In this stage
the thread is still alive.
Terminated : A thread enter the terminated state when it complete its task.

THE “main” THREAD

The “main” thread is a thread that begins running immediately when a java program starts
up. The “main” thread is important for two reasons:
5
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
1. It is the thread form which other child threads will be spawned.
2. It must be the last thread to finish execution because it performs various shutdown actions.

Although the main thread is created automatically when our program is started, it can be
controlled through a Thread object.
To do so, we must obtain a reference to it by calling the method currentThread().

Example:
class CurrentThreadDemo {
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(“Current Thread: “+t);

// change the name of the main thread


t.setName(“My Thread”);
System.out.println(“After name change : “+t);

try {
for(int n=5;n>0;n--) {
System.out.println(n);
Thread.sleep(1000);// delay for 1 second
}
} catch(InterruptedException e) {
System.out.println(“Main Thread Interrrupted”);
}
}
}

Output:
Current Thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1

6
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE

3.3: Creating Threads

We can create threads by instantiating an object of type Thread. Java defines two ways to
create threads:

1. By implementing Runnable interface (java.lang.Runnable)


2. By extending the Thread class (java.lang.Thread)

1. Creating threads by implementing Runnable interface:


 The Runnable interface should be implemented by any class whose instances are
intended to be executed as a thread.
 Implementing thread program using Runnable is preferable than implementing it by
extending Thread class because of the following two reasons:
1. If a class extends a Thread class, then it cannot extend any other class.
2. If a class Thread is extended, then all its functionalities get inherited. This is an
expensive operation.
 The Runnable interface has only one method that must be overridden by the class which
implements this interface:
public void run()// run() contains the logic of the thread
{
// implementation code
}
 Steps for thread creation:
1. Create a class that implements Runnable interface. An object of this class is
Runnable object.
public class MyThread implements Runnable
{
---

7
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
}
2. Override the run() method to define the code executed by the thread.
3. Create an object of type Thread by passing a Runnable object as argument.
Thread t=new Thread(Runnable threadobj, String threadName);
4. Invoke the start() method on the instance of the Thread class.
t.start();

 Example:
class MyThread implements Runnable
{

public void run()


{
for(int i=0;i<3;i++)
{
System.out.println(Thread.currentThread().getName()+" # Printing "+i);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
public class RunnableDemo {
public static void main(String[] args)
{
MyThread obj=new MyThread();
MyThread obj1=new MyThread();
Thread t=new Thread(obj,"Thread-1");
t.start();
Thread t1=new Thread(obj1,"Thread-2");
t1.start();
}
}

Output:
Thread-0 # Printing 0
Thread-1 # Printing 0
8
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Thread-1 # Printing 1
Thread-0 # Printing 1
Thread-1 # Printing 2
Thread-0 # Printing 2

2. Creating threads by extending Thread class:


Thread class provide constructors and methods to create and perform operations on a thread.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r, String name)
All the above constructors creates a new thread.

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public boolean isAlive(): tests if the thread is alive.
12. public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
13. public void suspend(): is used to suspend the thread(depricated).
14. public void resume(): is used to resume the suspended thread(depricated).
15. public void stop(): is used to stop the thread(depricated).
16. public boolean isDaemon(): tests if the thread is a daemon thread.
17. public void setDaemon(boolean b): marks the thread as daemon or user thread.
18. public void interrupt(): interrupts the thread.
19. public boolean isInterrupted(): tests if the thread has been interrupted.
20. public static boolean interrupted(): tests if the current thread has been interrupted.

 Steps for thread creation:

9
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
1. Create a class that extends java.lang.Thread class.
public class MyThread extends Thread
{
---
}
2. Override the run() method in the sub class to define the code executed by the thread.
3. Create an object of this sub class.
MyThread t=new MyThread(String threadName);
4. Invoke the start() method on the instance of the subclass to make the thread for
running.
start();
 Example:

class SampleThread extends Thread


{
public void run()
{
for(int i=0;i<3;i++)
{
System.out.println(Thread.currentThread().getName()+" # Printing "+i);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}

public class ThreadDemo {


public static void main(String[] args) {
SampleThread obj=new SampleThread();
obj.start();
SampleThread obj1=new SampleThread();
obj1.start();
}
}
Output:
Thread-0 # Printing 0

10
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
Thread-1 # Printing 0
Thread-1 # Printing 1
Thread-0 # Printing 1
Thread-0 # Printing 2
Thread-1 # Printing 2

3.3.1: THREAD PRIORITY

 Thread priority determines how a thread should be treated with respect to others.
 Every thread in java has some priority, it may be default priority generated by JVM or
customized priority provided by programmer.

 Priorities are represented by a number between 1 and 10.


1 – Minimum Priority5 – Normal Priority 10 – Maximum Priority
 Thread scheduler will use priorities while allocating processor. The thread which is
having highest priority will get the chance first.
 Thread scheduler is a part of Java Virtual Machine (JVM). It decides which thread
should execute first among two or more threads that are waiting for execution.
 It is decided based on the priorities that are assigned to threads. The thread having
highest priority gets a chance first to execute.
 If two or more threads have same priorities, we can’t predict the execution of waiting
threads. It is completely decided by thread scheduler. It depends on the type of algorithm
used by thread scheduler.
 Higher priority threads get more CPU time than lower priority threads.
 A higher priority thread can also preempt a lower priority thread. For instance, when a
lower priority thread is running and a higher priority thread resumes (for sleeping or
waiting on I/O), it will preempt the lower priority thread.
 If two or more threads have same priorities, we can’t predict the execution of waiting
threads. It is completely decided by thread scheduler. It depends on the type of algorithm
used by thread scheduler.

 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.
 To set a thread’s priority, use the setPriority() method.
 To obtain the current priority of a thread, use getPriority() method.

 Example:
11
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+
Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}

Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

3.4: Synchronizing Threads

Definition: Thread Synchronization


Thread synchronization is the concurrent execution of two or more threads that share critical
resources.
When two or more threads need to use a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process of ensuring single thread access to a
shared resource at a time is called synchronization.

Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts
may arise when parallel-running threads attempt to modify a common variable at the same time.
 Why use Synchronization
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

12
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
 Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

 Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This
can be done by two ways in java:
1. by synchronized method
2. by synchronized block

 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.

1. 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.

Syntax to use synchronized method:


Access_modifier synchronized return_type method_name(parameters)
{ …….. }

Example of java synchronized method:

class Table{
synchronized void printTable(int n)//synchronized method
{
for(int i=1;i<=5;i++) {
System.out.println(n*i);
try{ Thread.sleep(400); }
catch(Exception e) { System.out.println(e); }
}
13
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
}
}

class MyThread1 extends Thread {


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}

class MyThread2 extends Thread{


Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
} }
Output:
5
10
15
20
25
100
200
300
400
500

14
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
2. Synchronized block in java
 Synchronized block can be used to perform synchronization on any specific resource of
the method.
 Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
 If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to remember for Synchronized block


 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


1. synchronized (object reference expression) {
2. //code block
3. }

Example of synchronized block

class Table{
void printTable(int n)
{
synchronized(this)//synchronized block
{
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}

15
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronizedBlock1


{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);

t1.start();
t2.start();
}
}

Output:
5
10
15
20
25
100
200
300
400
500

Difference between synchronized method and synchronized block:


Synchronized method Synchronized block
1. Lock is acquired on critical block of
1. Lock is acquired on whole method.
code only.
2. Less preferred.
2. Preferred.
3. Performance will be less as compared to
3. Performance will be better as
synchronized block.
compared to synchronized method.
16
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE

3.5: Inter-Thread Communication

Inter-Thread Communication or Co-operation is all about allowing synchronized threads to


communicate with each other.
Definition: Inter-Thread Communication
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 and all these methods can be called only
from within a synchronized context.
S.No. Method & Description
1 public final void wait() throws InterruptedException
Causes the current thread to wait until another thread invokes the notify().
2 public final void wait(long timeout) throws InterruptedException
Causes current thread to wait until either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of time has elapsed.
Parameters:
timeout − the maximum time to wait in milliseconds.
3 public final void notify()
Wakes up a single thread that is waiting on this object's monitor.
4 Public final void notifyAll()
Wakes up all the threads that called wait( ) on the same object.
Difference between wait() and sleep()

Parameter wait() sleep()


wait should be called from
synchronized context i.e. from block
It need not be called from
Synchonized or method, If you do not call it using
synchronized block or methods
synchronized context, it will
throw IllegalMonitorStateException
Sleep method operates on
wait method operates on Object and
Calls on current thread and is in
defined in Object class
java.lang.Thread
wait release lock of object on which it
Sleep method does not release
Release of lock is called and also other locks if it
lock at all
holds any
until call notify() or notifyAll() from Until time expires or calls
Wake up condition
Object class interrupt()

17
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE

static wait is non-static method sleep is static method

Example: The following program illustrates simple bank transaction operations with inter-
thread communication:

class Customer{
int Balance=10000;

synchronized void withdraw(int amount)


{
System.out.println("going to withdraw..."+amount);

if(Balance<amount)
{
System.out.println("Less balance; Balance = Rs. "+Balance+"\nWaiting for deposit...\n");
try
{
wait();
}
catch(Exception e){}
}
Balance-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit... Rs. "+amount);
Balance+=amount;
System.out.println("deposit completed... Balance = "+Balance);
notify();
}
}

class ThreadCommn
{
public static void main(String args[]) {
Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(20000);}
}.start();
new Thread(){
public void run(){c.deposit(15000);}
18
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
}.start();
}
}

Output:

going to withdraw...20000
Less balance; Balance = Rs. 10000
Waiting for deposit...

going to deposit... Rs. 15000


deposit completed... Balance = 25000
withdraw completed...

3.6: Daemon Threads

Java offers two types of threads:


1) User Threads
2) Daemon Threads.

User Threads are threads which are created by the application or user. They are high-priority
threads. The JVM will wait for any user thread to complete its task before terminating it.

On the other hand, Daemon Threads are threads which are mostly created by the JVM. These
threads are low-priority threads whose only role is to provide services to user threads.

Definition: Daemon Threads


Daemon thread is a low priority thread that runs in background to perform tasks such as garbage
collection. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically.

Uses of Daemon Threads


Daemon threads are useful for background supporting tasks such as garbage collection,
releasing memory of unused objects and removing unwanted entries from the cache. Most of the
JVM threads are daemon threads.

Properties:
 A user thread can be changed to Daemon thread by using setDaemon() method of thread
class.
 public boolean isDaemon(): This method is used for checking the status of a thread. It
returns true if the thread is Daemon else it returns false.

19
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
 setDaemon() method can only be called before starting the thread. This method would
throw IllegalThreadStateException if you call this method after Thread.start() method.

Methods:
The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description

1) public void setDaemon(boolean is used to mark the current thread as daemon thread or
status) user thread.

2) public boolean isDaemon() is used to check that current thread is daemon or not.

Example:

public class DaemonThreadExample1 extends Thread{

public void run(){

if(Thread.currentThread().isDaemon()){
System.out.println("Daemon thread executing");
}
else{
System.out.println("user(normal) thread executing");
}
}
public static void main(String[] args){
DaemonThreadExample1 t1=new DaemonThreadExample1();
DaemonThreadExample1 t2=new DaemonThreadExample1();
t1.setDaemon(true);
t1.start();
t2.start();
}
}

Output:

Daemon thread executing


user(normal) thread executing

20
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE

3.7: Thread Groups

 Thread group in java is used to group similar threads into one unit. A thread group can
also contain other thread groups.
 Thread groups are constructed using java.lang.ThreadGroup class.
 The main use of thread groups is that you can handle multiple threads simultaneously.
 In such way, we can suspend, resume or interrupt group of threads by a single method
call.

Constructors of ThreadGroup class


There are only two constructors of ThreadGroupclass.

No. Constructor Description

1) ThreadGroup(String name) creates a thread group with given name.

2) ThreadGroup(ThreadGroup parent, creates a thread group with given parent group


String name) and name.

Important methods of ThreadGroup class


There are many methods in ThreadGroup class. A list of important methods are given below.

No. Method Description

1) int activeCount() returns no. of threads running in current group.

2) int activeGroupCount() returns a no. of active group in this thread group.

3) void destroy() destroys this thread group and all its sub groups.

4) String getName() returns the name of this group.

5) ThreadGroup getParent() returns the parent of this group.

6) void interrupt() interrupts all threads of this group.

7) void list() prints information of this group to standard console.

How To Add Threads To Thread Group

21
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
While creating the threads itself, specify it’s group using constructor which takes ThreadGroup
and name of a thread as arguments

EXAMPLE FOR THREADGROUP CLASS

class MyThread1 extends Thread


{
ThreadGroup tg;
MyThread1(ThreadGroup tg,String str)
{
super(tg,str);
this.tg=tg;
}
public void run()
{
for(int i=1;i<4;i++)
{
System.out.println(Thread.currentThread().getName()+" belongs to "+tg.getName()+" is Running..");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadGroupDemo
{
public static void main(String[] args)
{
//Creating Parent Thread Group
ThreadGroup tg = new ThreadGroup("Parent Thread Group");

//Adding threads to ThreadGroup while creating threads itself


MyThread1 t1 = new MyThread1(tg, "Thread 1");
t1.start();

MyThread1 t2 = new MyThread1(tg, "Thread 2");


t2.start();

System.out.println("Number of active threads in the group = "+tg.activeCount());

}
}

22
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE

Output:

Number of active threads in the group = 2


Thread 1 belongs to Parent Thread Group is Running..
Thread 2 belongs to Parent Thread Group is Running..
Thread 2 belongs to Parent Thread Group is Running..
Thread 1 belongs to Parent Thread Group is Running..
Thread 1 belongs to Parent Thread Group is Running..
Thread 2 belongs to Parent Thread Group is Running..

3.8: Exceptions

Definition:
Exceptions are events that occur during the execution of programs that interrupt the normal flow
of a program (e.g. divide by zero, array access out of bound, etc.).

1. In Java, an exception is an object that wraps an error event that occurred within a method
and contains:
o Information about the error including its type
o The state of the program when the error occurred
o Optionally, other custom information
2. Occurrence of any kind of exception in java applications may result in an abrupt
termination of the JVM or simply the JVM crashes.

Advantage of using Exceptions:

 Exceptions separate error handling code from regular code.


o Benefit: Cleaner algorithms, less clutter
 Exceptions propagate errors up the call stack.
o Benefit: Nested methods do not have to explicitly catch-and-forward errors (less
work, more reliable)
 Exception classes group and differentiate error types.
o You can group errors by their generalize parent class, or
o Differentiate errors by their actual class
 Exceptions standardize error handling.

23
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE

3.9: Exception Hierarchy

All exceptions and errors extend from a common java.lang.Throwable parent class.

The Throwable class is further divided into two classes:


1. Exceptions and
2. Errors.

Exceptions: Exceptions represents errors in the Java application program, written by the user.
Because the error is in the program, exceptions are expected to be handled, either
 Try to recover it if possible
 Minimally, enact a safe and informative shutdown.

Sometimes it also happens that the exception could not be caught and the program may get
terminated. Eg. ArithmeticException

An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
 A user has entered an 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.

Errors: Errors represent internal errors of the Java run-time system which could not be handled
easily. Eg. OutOfMemoryError.

24
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE
DIFFERENCE BETWEEN EXCEPTION AND ERROR:

S.No. Exception Error


1. Exceptions can be recovered Errors cannot be recovered
Exceptions are of type Errors are of type java.lang.Error
2.
java.lang.Exception
Exceptions can be classified into two There is no such classification for
types: errors. Errors are always unchecked.
3.
a) Checked Exceptions
b) Unchecked Exceptions
In case of Checked Exceptions, compiler In case of Errors, compiler won’t have
will have knowledge of checked knowledge of errors. Because they
exceptions and force to keep try…catch happen at run time.
4.
block. Unchecked Exceptions are not
known to compiler because they occur at
run time.
Exceptions are mainly caused by the Errors are mostly caused by the
5. application itself. environment in which application is
running.
Examples: Examples:
Checked Exceptions: Java.lang.StackOverFlowError,
SQLException, IOException java.lang.OutOfMemoryError
6.
Unchecked Exceptions:
ArrayIndexOutOfBoundsException,
NullPointerException
EXCEPTION HIERARCHY

25
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE

Types of Exceptions:
1. Checked Exceptions
2. Unchecked Exceptions

1. Checked Exceptions:

 The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions
 It is an exception that is typically a user error or a problem that cannot foreseen by the
programmer.
 Checked exceptions are checked at compile-time.
 Checked Exceptions forces programmers to deal with the exception that may be thrown.
 Checked exceptions must be caught using try.. catch () block or we should throw the
exception using throws clause. If you dont, compilation of program will fail.

Example:
1. ClassNotFoundException 5. NoSuchFileException
2. CloneNotSupportedException 6. NoSuchMethodException
3. IllegalAccessException, 7. IOException
4. MalformedURLException.

Example Program: (Checked Exception)

FileNotFoundException is a checked exception in Java. Anytime, we want to read a file


from filesystem, Java forces us to handle error situation where file may not be present in
place.
Without try-catch
import java.io.*;

public class CheckedExceptionExample {


public static void main(String[] args)
{
FileReader file = new FileReader("src/somefile.txt");
}
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:


Unhandled exception type FileNotFoundException

To make program able to compile, you must handle this error situation in try-catch block.
Below given code will compile absolutely fine.

26
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
Panimalar Engineering College Department of CSE

With try-catch
import java.io.*;

import java.io.*;

public class CheckedExceptionExample {


public static void main(String[] args)
{
try
{
@SuppressWarnings("resource")
FileReader file = new FileReader("src/somefile.java");
System.out.println(file.toString());
}
catch(FileNotFoundException e)
{
System.out.println("Sorry...Requested resource not availabe...");
}
}
}

Output:

Sorry...Requested resource not availabe...

2. Unchecked Exceptions(RunTimeException):

 The classes that extend RuntimeException are known as unchecked exceptions.


 Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
 Unchecked exceptions , however, the compiler doesn’t force the programmers to
either catch the exception or declare it in a throws clause.
 In fact, the programmers may not even know that the exception could be thrown.
 They are either irrecoverable (Errors) and the program should not attempt to deal
with them, or they are logical programming errors. (Runtime Exceptions).
Example:
1. ArrayIndexOutOfBoundsException
2. ArithmeticException
3. NullPointerException.

27
23IT1301– Object Oriented Programming – III Semester CSE Unit - 3
28

Panimalar Engineering College Department of CSE

Example: Unchecked Exception

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.

class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


at Main.main(Main.java:5)

Exception Handling

What is exception handling?


Exception Handling is a mechanism to handle runtime errors, such as
ClassNotFoundException, IOException, SQLException, RemoteException etc. by taking the
necessary actions, so that normal flow of the application can be maintained.

JAVA EXCEPTION HANDLING KEYWORDS

Exception handling in java is managed using the following five keywords:


S.No. Keyword Description
1 try A block of code that is to be monitored for exception.
The catch block handles the specific type of exception along with
2 catch the try block. For each corresponding try block there exists the catch
block.
It specifies the code that must be executed even though exception
3 finally
may or may not occur.
This keyword is used to explicitly throw specific exception from the
4 throw
program code.
It specifies the exceptions that can be thrown by a particular
5 throws
method.

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


29

Panimalar Engineering College Department of CSE

 try Block:
 The java code that might throw an exception is enclosed in try block. It must be used
within the method and must be followed by either catch or finally block.
 If an exception is generated within the try block, the remaining statements in the try
block are not executed.

 catch Block:
 Exceptions thrown during execution of the try block can be caught and handled in a
catch block.
 On exit from a catch block, normal execution continues and the finally block is
executed.

 finally Block:
A finally block is always executed, regardless of the cause of exit from the try block, or
whether any catch block was executed.
 Generally finally block is used for freeing resources, cleaning up, closing connections
etc.
 Even though there is any exception in the try block, the statements assured by finally
block are sure to execute.
 Rule:
 For each try block there can be zero or more catch blocks, but only one finally
block.
 The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).
The try-catch-finally structure(Syntax):

try {
// Code block
}
catch (ExceptionType1 e1) {
// Handle ExceptionType1 exceptions
}
catch (ExceptionType2 e2) {
// Handle ExceptionType2 exceptions
}
// ...
finally {
// Code always executed after the
// try and any catch block
}

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


30

Panimalar Engineering College Department of CSE

Rules for try, catch and finally Blocks:

1) Statements that might generate an exception are placed in a try block.


2) Not all statements in the try block will execute; the execution is interrupted if an
exception occurs
3) For each try block there can be zero or more catch blocks, but only one finally block.
4) The try block is followed by
i. one or more catch blocks
ii. or, if a try block has no catch block, then it must have the finally block
5) A try block must be followed by either at least one catch block or one finally block.
6) A catch block specifies the type of exception it can catch. It contains the code known
as exception handler
7) The catch blocks and finally block must always appear in conjunction with a try
block.
8) The order of exception handlers in the catch block must be from the most specific
exception

Program without Exception handling: (Default exception handler):

class Simple
{
public static void main(String args[])
{
int data=50/0;

System.out.println("rest of the code...");


}
}

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


As displayed in the above example, rest of the code is not executed i.e. rest of the
code... statement is not printed.

Program Explanation:

The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


31

Panimalar Engineering College Department of CSE

 Prints out exception description.


 Prints the stack trace (Hierarchy of methods where the exception occurred).
 Causes the program to terminate.

Example:
public class Demo
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


32

Panimalar Engineering College Department of CSE

}
}
Output: java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...

Nested Try Block

Definition: try block within a try block is known as nested try block.

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.
 If an inner try statement does not have a matching catch statement for a particular exception,
the control is transferred to the next try statement’s catch handlers that for a matching catch
statement.
 If none of the catch statement match, then the Java run-time system will handle the
exception.
Syntax:
Example: ....
try
class NestedExcep {
{ statement 1;
public static void main(String[] args) statement 2;
try
{ {
try statement 1;
{ statement 2;
int arr[]={1,5,4,10}; }
catch(Exception e)
try {
{ }
int x=arr[3]/arr[1]; }
catch(Exception e)
System.out.println("Quotient = "+x);
{
}
....
23IT1301 – Object Oriented Programming – III Sem CSE Unit 3
33

Panimalar Engineering College Department of CSE

}
catch(ArithmeticException ae)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index out of bound exception");
}
System.out.println("...End of Program...");
}
}
Output:
Quotient = 2
array index out of bound exception
...End of Program...

Multiple catch blocks


Multiple catch is used to handle many different kind of exceptions that may be generated while
running the program. i.e more than one catch clause in a single try block can be used.

Rules:
 At a time only one Exception can occur and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception.

Syntax:

try {
// Code block
}

catch (ExceptionType1 e1) {


// Handle ExceptionType1 exceptions
}
catch (ExceptionType2 e2) {
// Handle ExceptionType2 exceptions
}

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


34

Panimalar Engineering College Department of CSE

Example:

public class MultipleCatchBlock2 {

public static void main(String[] args) {

try
{
int a[]= {1,5,10,15,16};
System.out.println("a[1] = "+a[1]);
System.out.println("a[2]/a[3] = "+a[2]/a[3]);
System.out.println("a[5] = "+a[5]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


35

Panimalar Engineering College Department of CSE

System.out.println("rest of the code");


}
}

Output:

a[1] = 5
a[2]/a[3] = 0
ArrayIndexOutOfBounds Exception occurs
rest of the code

3.10: THROWING AND CATCHING EXCEPTIONS

Before catching an exception, it is must to throw an exception first. This means that
there should be a code somewhere in the program that could catch exception thrown in the
try block.

An exception can be thrown explicitly


1. Using the throw statement
2. Using the throws statement

1: Using the throw statement


 A program can explicitly throw an exception using the throw statement besides the
implicit exception thrown.
 We can throw either checked, uncheked exceptions or custom(user defined) exceptions
 When throw statement is called:
1) It causes the termination of the normal flow of control of the program code and stops
the execution of the subsequent statements.
2) It transfers the control to the nearest catch block handling the type of exception object
thrown
3) If no such catch block exists, then the program terminates.

The general format of the throw statement is as follows:


throw <exception reference>;

The Exception reference must be of type Throwable class or one of its subclasses. A detail
message can be passed to the constructor when the exception object is created.
Example:

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


36

Panimalar Engineering College Department of CSE

1) public class ThrowDemo


2) {
3) static void validate(int age)
4) {
5) if(age<18)
6) throw new ArithmeticException("not valid");
7) else
8) System.out.println("welcome to vote");
9) }
10) public static void main(String args[])
11) {
12) validate(13);
13) System.out.println("rest of the code...");
14) }
15) }

Output:

Exception in thread "main" java.lang.ArithmeticException: not valid


at ThrowDemo.validate(ThrowDemo.java:6)
at ThrowDemo.main(ThrowDemo.java:12)

In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.

2: Using throws keyword:


 The throws statement is used by a method to specify the types of exceptions the
method throws.
 If a method is capable of raising an exception that it does not handle, the method must
specify that the exception have to be handled by the calling method.
 This is done using the throws clause. The throws clause lists the types of exceptions
that a method might throw.
Syntax:

Return-type method_name(arg_list) throws exception_list


{
// method body
}

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


37

Panimalar Engineering College Department of CSE

Example:

1. import java.util.Scanner;
2. public class ThrowsDemo
3. {
4. static void divide(int num, int din) throws ArithmeticException
5. {
6. int result=num/din;
7. System.out.println("Result : "+result);
8. }

9. public static void main(String args[])


10. {
11. int n,d;
12. Scanner in=new Scanner(System.in);
13. System.out.println("Enter the Numerator : ");
14. n=in.nextInt();
15. System.out.println("Enter the Denominator : ");
16. d=in.nextInt();
17. try
18. {
19. divide(n,d);
20. }
21. catch(Exception e)
22. {
23. System.out.println(" Can't Handle : divide by zero ERROR");
24. }
25. System.out.println(" ** Continue with rest of the code ** ");
26. }
27. }

Output:
Enter the Numerator :
4
Enter the Denominator :
0
Can't Handle : divide by zero ERROR
** Continue with rest of the code **
Enter the Numerator :
6
Enter the Denominator :
2

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


38

Panimalar Engineering College Department of CSE

Result : 3
** Continue with rest of the code **

Difference between throw and throws:


throw keyword throws keyword
1) throw is used to explicitly throw an
throws is used to declare an exception.
exception.
2) checked exception cannot be checked exception can be propagated with
propagated without throws. throws.
3) throw is followed by an instance. throws is followed by class.
4) throw is used within the method. throws is used with the method signature.
You can declare multiple exception
5)You cannot throw multiple exception e.g. public void method()throws
IOException,SQLException.

3.11: 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.
S. No. Exception Description
Thrown when a problem in arithmetic
1. ArithmeticException
operation is noticed by the JVM.
Thrown when you access an array with an
2. ArrayIndexOutOfBoundsException
illegal index.
Thrown when you try to access a class
3. ClassNotFoundException
which is not defined
Thrown when you try to access a non-
4. FileNotFoundException
existing file.
Thrown when the input-output operation
5. IOException
has failed or interrupted.
Thrown when a thread is interrupted when
6. InterruptedException
it is processing, waiting or sleeping
7. IllegalAccessException Thrown when access to a class is denied
Thrown when you try to access any field or
8. NoSuchFieldException
variable in a class that does not exist
Thrown when you try to access a non-
9. NoSuchMethodException
existing method.
10. NullPointerException Thrown when you refer the members of a

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


39

Panimalar Engineering College Department of CSE

null object
Thrown when a method is unable to
11. NumberFormatException
convert a string into a numeric format
Thrown when you access a String array
12. StringIndexOutOfBoundsException
with an illegal index.

Example 1: NullPointer Exception


//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}

Output:
NullPointerException..

Example 2: NumberFormat Exception


// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}

Output:

Number format exception

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


40

Panimalar Engineering College Department of CSE

3.12: USER-DEFINED EXCEPTIONS (creating own exceptions)

Exception types created by the user to describe the exceptions related to their applications are
known as User-defined Exceptions or Custom Exceptions.

To create User-defined Exceptions:


1. Pick a self-describing *Exception class name.
2. Decide if the exception should be checked or unchecked.
 Checked : extends Exception
 Unchecked: extends RuntimeException
3. Define constructor(s) that call into super class constructor(s), taking message that can
be displayed when the exception is raised.
4. Write the code that might generate the defined exception inside the try-catch block.
5. If the exception of user-defined type is generated, handle it using throw clause as
follows:
throw ExceptionClassObject;
Example:

The following program illustrates how user-defined exceptions can be created and thrown.

public class EvenNoException extends Exception


{
EvenNoException(String str)
{
super(str); // used to refer the superclass constructor
}

public static void main(String[] args)


{
int arr[]={2,3,4,5};
int rem;
int i;
for(i=0;i<arr.length;i++)
{
rem=arr[i]%2;
try
{
if(rem==0)
{
System.out.println(arr[i]+" is an Even Number");

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


41

Panimalar Engineering College Department of CSE

}
else
{
EvenNoException exp=new EvenNoException(arr[i]+" is
not an Even Number");
throw exp;
}
}
catch(EvenNoException exp)
{
System.out.println("Exception thrown is "+exp);
}
} // for loop
} // main()
} // class

Output:

2 is an Even Number
Exception thrown is EvenNoException: 3 is not an Even Number
4 is an Even Number
Exception thrown is EvenNoException: 5 is not an Even Number

Program Explanation:
In the above program, the EvenNumberException class is created which inherits the Exception
super class. Then the constructor is defined with the call to the super class constructor. Next, an
array arr is created with four integer values. In the main(), the array elements are checked one
by one for even number. If the number is odd, then the object of EvenNumberException class is
created and thrown using throw clause. The EvenNumberException is handled in the catch
block.

Comparison Chart - final Vs. finally Vs. finalize

Basis for
final finally finalize
comparison

Basic Final is a Finally is a "block" in Finalize is a "method" in


"Keyword" and Java. Java.
"access modifier"
in Java.

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


42

Panimalar Engineering College Department of CSE

Basis for
final finally finalize
comparison

Applicable Final is a keyword Finally is a block that finalize() is a method


applicable to is always associated applicable to objects.
classes, variables with try and catch
and methods. block.

Working (1) Final variable A "finally" block, Finalize method


becomes constant, clean up the resources performs cleans up
and it can't be used in "try" block. activities related to the
reassigned. object before its
(2) A final method destruction.
can't be overridden
by the child class.
(3) Final Class can
not be extended.

Execution Final method is "Finally" block finalize() method


executed upon its executes just after the executes just before the
call. execution of"try-catch" destruction of the object.
block.

Example class FinalExample{ class FinallyExample{ class FinalizeExample{


public static void public static void public void
main(String[] args){ main(String[] args){ finalize(){System.out.println("fi
final int x=100; try{ nalize called");}
x=200;//Compile Time int x=300; public static void main(String[]
Error }catch(Exception args){
}} e){System.out.println(e);} FinalizeExample f1=new
finally{ FinalizeExample();
System.out.println("finally FinalizeExample f2=new
block is executed"); FinalizeExample();
} f1=null;
}} f2=null;
System.gc();
}}

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


43

Panimalar Engineering College Department of CSE

3.13: STACK TRACE ELEMENTS

A Stack Trace is a list of method calls from the point when the application was started
to the current location of execution within the program. A Stack Trace is produced
automatically by the Java Virtual Machine when an exception is thrown to indicate the
location and progression of the program up to the point of the exception. They are
displayed whenever a Java program terminates with an uncaught exception.
 We can access the text description of a stack trace by calling the printStackTrace()
method of the Throwable class.
 The java.lang.StackTraceElement is a class where each element represents a single
stack frame.
 We can call the getStackTrace() method to get an array of StackTraceElement
objects that we want analyse in our program.

Class Declaration
Following is the declaration for java.lang.StackTraceElement class
public final class StackTraceElement extends Object implements Serializable

Class constructors
Constructor & Description
StackTraceElement(String declaringClass, String methodName, String fileName, int
lineNumber)
This creates a stack trace element representing the specified execution point.

Parameters:
 declaringClass – the fully qualified name of the class containing the execution point
represented by the stack trace element.
 methodName – the name of the method containing the execution point represented by
the stack trace element.
 fileName – the name of the file containing the execution point represented by the stack
trace element, or null if this information is unavailable
 lineNumber – the line number of the source line containing the execution point
represented by this stack trace element, or a negative number if this
information is unavailable. A value of -2 indicates that the method
containing the execution point is a native method.
Throws: NullPointerException – if declaringClass or methodName is null.

Methods in StackTraceElement class:


Method Name Description
String getFileName() Gets the name of the source file containing the

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


44

Panimalar Engineering College Department of CSE

execution point represented by the


StackTraceElement.
int getLineNumber() Gets the line number of the source file containing the
execution point represented by the
StackTraceElement.
String getClassName() Gets the fully qualified name of the class containing
the execution point represented by the
StackTraceElement.
String getMethodName() Gets the name of the method containing the
execution point represented by the
StackTraceElement.
boolean isNativeMethod() Returns true if the execution point of the
StackTraceElement is inside a native method.
String toString() Returns a formatted string containing the class name,
method name, file name and the line number, if
available.

Example:

The following program for finding factorial(using recursion) prints the stack trace of a
recursive factorial function.

import java.util.Scanner;

public class StackTraceTest


{
public static int factorial(int n)
{
System.out.println(" Factorial ("+n+"):");
Throwable t=new Throwable();
StackTraceElement[] frames=t.getStackTrace();
for(StackTraceElement f:frames)
{
System.out.println(f);
}
int r;
if(n<=1)
r=1;
else
r=n*factorial(n-1);

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3


45

Panimalar Engineering College Department of CSE

System.out.println("return "+r);
return r;
}

public static void main(String[] args)


{
Scanner in=new Scanner(System.in);
System.out.println("Enter n: ");
int n=in.nextInt();
factorial(n);
}
}

Output:
Enter n: 3
Factorial (3):
StackTraceTest.factorial(StackTraceTest.java:10)
StackTraceTest.main(StackTraceTest.java:30)
Factorial (2):
StackTraceTest.factorial(StackTraceTest.java:10)
StackTraceTest.factorial(StackTraceTest.java:20)
StackTraceTest.main(StackTraceTest.java:30)
Factorial (1):
StackTraceTest.factorial(StackTraceTest.java:10)
StackTraceTest.factorial(StackTraceTest.java:20)
StackTraceTest.factorial(StackTraceTest.java:20)
StackTraceTest.main(StackTraceTest.java:30)
return 1
return 2
return 6

23IT1301 – Object Oriented Programming – III Sem CSE Unit 3

You might also like