OOPJ Module 3
OOPJ Module 3
Exception Handling: Concepts of exception handling, Types of exceptions, Usage of try, catch,
throw, throws and finally keywords, Built-in exceptions, Creating user defined exception;
Multithreading: Concepts of multithreading, Differences between process and thread, Thread
life cycle, Creating multiple threads using Thread class and Runnable interface, Synchronization,
Thread priorities, Inter thread communication.
Exception Handling
Exception:
Exception is an abnormal condition that arises in a code sequence at a run time and disrupts the
normal flow of the program.
It can be caught and handled by program or code.
An object is created when an exception occurs. This object is called exception object and contains
information like, name and description of exception along with the state of the program.
There is always a reason behind an exception. Following are the reason why exception can occur in
the code:
Invalid input of the users
Failure of device
Weak network connection
Limitation of resources
Errors in code (syntax or logical error)
Opening a file that is unavailable
Types of Exceptions:
There are two types of exceptions in java:
1. Checked exceptions (95% of exceptions in java are checked):
2. Unchecked exceptions (5% of exceptions in java are unchecked)
Page | 1
1. Checked Exceptions
The exceptions that are checked at compilation time by java compiler are called checked
exceptions.
In case of checked exceptions, the programmer should either handle them or throw without
handling them.
Programmer cannot ignore checked exceptions as java compiler will remind of exception until
taken care off.
Example:
Exception Description
IOExcepion IO activity could not be performed.
ClassNotFoundException Class not found exception
IIlegalAccessException Access to a class is denied
2. Unchecked Exceptions
The exceptions that are checked by the JVM at runtime are called unchecked exceptions.
Programmers can write a java program with unchecked exceptions and can compile the
program.
Programmer can see their effect only when he/she runs the program.
Example:
Exception Description
ArithmeticException Arithemetic eror, such as divide by zero
Page | 2
Exception Hierarchy:
Object Class:
Object class is present in java.lang package. \
Every class in Java is directly or indirectly derived from the Object class.
If a class does not extend any other class, then it is a direct child class of Object and if extends another
class then it is indirectly derived.
Therefore, the Object class methods are available to all Java classes.
Hence Object class acts as a root of the inheritance hierarchy in any Java Program.
Page | 3
Throwable Class:
The Throwable class is the superclass of every error and exception in the Java language.
Only objects that are one of the subclasses this class are thrown by any “Java Virtual Machine” or may
be thrown by the Java throw statement.
For the motives of checking of exceptions during compile-time, Throwable and any subclass of
Throwable which is not also a subclass of either Error or RuntimeException are considered as checked
exceptions.
Throwable class is the root class of Java Exception Hierarchy and is inherited by two subclasses:
1. Exception
2. Error
Exception Handling:
Exception handling helps program to prevent abnormal crashing.
Whenever an exception occurs inside a method, an exception object is created by a method and is
handed over to the JVM, this is called default exception handling.
There are 5 keywords used in java exception handling:
1. try
2. catch
3. finally
4. throw
5. throws
Keyword Description
Page | 4
try catch block:
Syntax
try {
Statement1;
Statement2;
….
}
catch(Exception-type e){
Statementa;
Statement;
….
}
Note: No statement is allowed in between try and catch block. Catch block argument is always of type
throwable.
Example:
Consider two integers x and y as input and compute the value of x/y. Implement a class which raise an
exception if y is zero.
Program:
Page | 5
Page | 6
try with multi-catch:
We could use multiple catch blocks with single try block to handle different type of exception similarly.
Syntax
try {
Statement1;
Statement2;
….
}
catch(Exception e1){
Statementa;
}
catch(Exception e2){
statementb;
}
Example:
Consider two integers x and y as input and compute the value of x/y. Implement a class which raise an
exception if x and y are not signed integers or if y is zero. Use try-multi catch block.
Program:
Page | 7
Page | 8
finally keyword:
Syntax
try {
Statement1;
Statement2;
….
}
catch(Exception-type e){
Statementa;
Statement;
….
}
finally {
System.out.pritln(“done”);
}
Example:
Consider two integers x and y as input and compute the value of x/y. Implement a class which raise an
exception if y is zero. Use finally block.
Page | 9
Page | 10
throw Keyword:
Syntax:
throw new exception_class("error message");
Example:
Consider two integers x and y as input and compute the value of x/y. Implement a class which throw an
Arithmetic Exception if y is zero.
Page | 11
throws Keyword:
Syntax:
Page | 12
Differences Between throw vs throws:
Page | 13
Nested try block:
When a try block is written inside another try block is called nested try.
Example:
Consider two integers x and y as input and compute the value of x/y. Implement a class which raise an
exception if x and y are not signed integers or if y is zero. Use nested try.
Program:
Page | 14
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.
1. ArithmeticException:
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBounds Exception:
It is thrown to indicate that an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
3. ClassNotFoundException:
This Exception is raised when we try to access a class whose definition is not found.
4. NullPointerException:
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
5. NoSuchMethodException:
Programs
1. Write a Java Program that illustrates ArithmeticException.
Page | 15
2. Write a Java Program that illustrates ArrayIndexOutOfBounds Exception.
Page | 16
3. Write a Java Program that illustrates ClassNotFoundException.
Page | 17
4. Write a Java Program that illustrates NullPointerException.
Page | 18
5. Write a Java Program that illustrates NoSuchMethodException.
Page | 19
User defined exception:
Creating our own Exception is known as custom exception or user-defined exception.
In Java, we can create our own exceptions that are derived classes of the Exception class.
Create User-Defined Exceptions:
o To create a custom exception in java, we have to create a class by extending it with an Exception
class from the java.lang package.
o Below is the template to be followed for creating a user-defined exception in java.
public class SimpleCustomException extends Exception{
}
Example:
Write a Java Program to define an user defined exception called InvalidAgeException. Program takes
an integer into variable age. If age is lessthan 18 then it raises InvalidAgeException with string “Age
not Valid for Vote”, else display the message as “Eligible to Vote”.
Page | 20
Chained Exceptions:
Chained Exceptions allows to relate one exception with another exception, i.e one exception describes
cause of another exception.
For example, consider a situation in which a method throws an ArithmeticException because of an
attempt to divide by zero but the actual cause of exception was an I/O error which caused the divisor
to be zero. The method will throw only ArithmeticException to the caller. So the caller would not come
to know about the actual cause of exception.
Example:
Write a java program that demonstrates chained exceptions.
Page | 21
Multithreading
Process -- Definition:
A process is a program in execution.
Program VS Process:
A program is a passive entity, such as a file containing a list of instructions stored on disk (also called an
executable file).
A process is an active entity, with a program counter specifying the next instruction to execute and a set
of associated resources.
Thread - Definition:
A thread is an extremely lightweight process, or the smallest component of the process, that enables
software to work more effectively by doing numerous tasks concurrently.
Page | 22
Process VS Thread
S.NO Process Thread
3 The process takes more time to terminate. The thread takes less time to terminate.
4 It takes more time for creation. It takes less time for creation.
Multithreading:
Multithreading is a process of executing multiple threads simultaneously.
Page | 23
Thread Life Cycle:
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
The diagram shown below represents various states of a thread at any instant in time.
Start Stop
Yield
Killed Thread
Suspend Resume
Sleep Notify Stop
Wait
1) Newborn: The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable: The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.
3) Running: The thread is in running state if the thread scheduler has selected it.
4) Blocked(Non-Runnable) : This is the state when the thread is still alive, but is currently not eligible
to run.
5) Dead(Terminated): A thread is in terminated or dead state when its run() method exits.
Page | 24
Main Thread:
When a Java program starts up, one thread begins running immediately. This is usually called the main
thread of your program, because it is the one that is executed when your program begins.
The main thread is important for two reasons:
1. It is the thread from which other “child” threads will be spawned.
2. Often, it must be the last thread to finish execution because it performs various shutdown
actions.
Although the main thread is created automatically when your program is started, it can be controlled
through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread( ),
which is a public static member of Thread. Its general form is shown here:
static Thread currentThread( )
This method returns a reference to the thread in which it is called. Once you have a reference to the
main thread, you can control it just like any other thread.
Let’s begin by reviewing the following example:
public class MainThreadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
System.out.println("Current Thread: "+t);
}
}
Output:
Current Thread: Thread[main,5,main]
This displays, in order: the name of the thread, its priority, and the name of its group. By default, the
name of the main thread is main. Its priority is 5, which is the default value, and main is also the name of the
group of threads to which this thread belongs.
Page | 25
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 int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
Creating Threads:
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Page | 26
Creating Thread by extending Thread Class:
We can make our class runnable as thread by extending the class Thread. This gives us access to all the
thread methods directly. It includes the following steps:
Step1: Declare the class as extending the Thread class.
The Thread class can be extended as follows:
class MyThread extends Thread
{
----
----
----
}
Now we have a new type of thread My Thread.
Step2: Override the run( ) method that is responsible for executing the sequence of code that the
thread will execute.
public void run( )
{
----
---- // Thread code here
----
}
Step3: Create a thread object and call the start( ) method to initiate the thread execution.
MyThread aThread = new MyThread( ):
aThread.start( ): // invokes run() method
Example:
Write a Java Program that creates a thread by extending Thread class.
Page | 27
Who makes your class object as thread object?
Thread class constructor allocates a new thread object. When you create object of
ExtendingThreadClass class, your class constructor is invoked(provided by Compiler) from where Thread
class constructor is invoked(by super() as first statement).So your ExtendingThreadClass class object is thread
object now.
Can we start a thread twice?
No. After staring a thread, it can never be started again. If you does so, an IllegalThreadStateException
is thrown.
What if we call run() method directly instead start() method?
Each thread starts in a separate call stack.
Invoking the run() method from main thread, the run() method goes onto the current call stack rather
than at the beginning of a new call stack.
Page | 28
Example:
Write a Java Program that creates a thread by extending Runnable class.
Page | 29
Programs
Write a Java Program that creates a thread with a specified name, and print the name and id of the
thread.
Description:
Use setName( ) method to set a name to a thread.
Use getName( ) method to get a name of a thread.
Use getId( ) method to get an ID of a threas.
Program:
Page | 30
Write a Java Program that creates 2 threads, and start the both threads immediately and print the
names of the threads.
Description:
Use currentThread() method which returns a reference to the currently executing thread object.
Program:
Page | 31
Write a Java Program that creates 2 threads, each thread prints numbers from 1 to 5 and also each
thread sleeps 500 milliseconds.
Description:
Use sleep( ) method to sleep a thread for the specified milliseconds of time.
Program:
Page | 32
Write a java program that implements a multi-thread application that has three threads. First thread
generates random integer every 1 second and if the value is even, second thread computes the square
of the number and prints. If the value is odd, the third thread will print the value of cube of the
number.
Program:
Page | 33
Write a program that creates three threads. First thread displays “Good Morning” every one second,
the second thread displays “Hello” every two seconds and the third thread displays “Welcome” every
three seconds.
Program:
Page | 34
Thread priorities:
Each thread has a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling).
But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
3 priority 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.
Example:
1. Write a Java Program that creates a thread and print priority of it.
Description:
Use getPriority( ) method to get a priority of a thread.
Program:
Page | 35
2. Write a Java Program that creates 2 threads and print priority of each of them.
Program:
Page | 36
3. Write a Java Program that creates 2 threads and set priority of first thread as 1 and second
thread as 10, and display them.
Description:
Use setPriority ( ) method to set a priority to a thread.
Program:
Page | 37
Synchronization in Java
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.
Page | 38
Page | 39
Thread Synchronization:
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
2. Cooperation (Inter-thread communication)
1. Mutual Exclusive:
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be
done by three ways in java:
1. Synchronized Method
2. Synchronized Block
3. Static Synchronization
1. Synchronized method:
It is a method that can be declared synchronized using the keyword “synchronized” before the method
name. By writing this, it will make the code in a method thread-safe so that no resources are shared when the
method is executed.
Syntax:
synchronized public void methodName( ) { }
Example:
Page | 40
Page | 41
2. Synchronized Block:
If a block is declared as synchronized then the code which is written inside a method is only executed
instead of the whole code. It is used when sequential access to code is required.
Syntax:
synchronized (object reference)
{
// Insert code here
}
Example:
Page | 42
Page | 43
3. Static Synchronization:
The method is declared static in this case. It means that lock is applied to the class instead of an object
and only one thread will access that class at a time.
Syntax:
synchronized static return_type method_name{ }
Example:
Page | 44
Page | 45
2. Inter-thread communication:
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. It is
implemented by following methods of Object class:
1. wait( )
2. notify( )
3. notifyAll( )
1. wait( ) method:
The wait( ) method causes current thread to release the lock and wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.
Method Description
public final void wait( )throws InterruptedException It waits until object is notified.
public final void wait(long timeout)throws InterruptedException It waits for the specified amount of time.
2. notify() method
The notify( ) method wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
Syntax:
public final void notify( )
3. notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll( )
Understanding the process of inter-thread communication:
Page | 46
The point to point explanation of the above diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock
and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
Example
Page | 47
Page | 48
Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?
It is because they are related to lock and object has a lock.
Difference between wait and sleep?
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It is a method of Object class It is a method of Thread class
It is the non-static method It is the static method
It should be notified by notify() or After the specified amount of time, sleep is
notifyAll() methods completed
Page | 49