OOPJ Module-3
OOPJ Module-3
Exception Handling
Exception:
Exception is an abnormal condition that arises in a code sequence at a run
Page | 1
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 | 2
1. Checked Exceptions
The exceptions that are checked at compilation time by the Java compiler
Excepti Descripti
on on
IOExcepion IO activity could not be performed.
ClassNotFoundException Class not found exception
IIlegalAccessException Access to a class is denied
2. Unchecked Exceptions
3.
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:
Excepti Descripti
on on
ArithmeticException Arithemetic eror, such as divide by
zero
ArrayIndexOutOfBoundsExc Array index is out of bound
eption
NegativeArraySizeException Array created with a negative size
Object Class:
Object class is present in [Link] 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
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
Page |05
Keyword Description
The "try" keyword is used to specify a block where we
try should place an exception code.
It means we can't use try block alone.
The try block must be followed by either catch or finally.
There are given some scenarios where unchecked exceptions may occur. They are as
follows:
1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws
a NullPointerException.
1. String s=null;
2. [Link]([Link]());//NullPointerException
3) A scenario where NumberFormatException occurs
Page |05
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.
1. String s="abc";
2. int i=[Link](s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.
If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that will
not throw an exception.
Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception ( i.e.,
Page |05
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.
The catch block must be used after the try block only. You can use multiple catch block
with a single try block.
Example 1
[Link]
Output:
Let's see the solution of the above problem by a java try-catch block.
Example 2
[Link]
Page |05
5. int data=50/0; //may throw exception
6. }
7. //handling the exception
8. catch(ArithmeticException e)
9. {
10. [Link](e);
11. }
12. [Link]("rest of the code");
13. }
14.
15.}
Test it Now
Output:
[Link]: / by zero
rest of the code
A try block can be followed by one or more catch blocks. Each catch block must contain
a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.
Points to remember
o At a time only one exception occurs and at a time only one catch block is
executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Example 1
[Link]
Page |05
3. public static void main(String[] args) {
4.
5. try{
6. int a[]=new int[5];
7. a[5]=30/0;
8. }
9. catch(ArithmeticException e)
10. {
11. [Link]("Arithmetic Exception occurs");
12. }
13. catch(ArrayIndexOutOfBoundsException e)
14. {
15. [Link]("ArrayIndexOutOfBounds Exception occurs");
16. }
17. catch(Exception e)
18. {
19. [Link]("Parent Exception occurs");
20. }
21. [Link]("rest of the code");
22. }
23.}
Test it Now
Output:
Example 2
[Link]
Page |05
7.
8. [Link](a[10]);
9. }
10. catch(ArithmeticException e)
11. {
12. [Link]("Arithmetic Exception occurs");
13. }
14. catch(ArrayIndexOutOfBoundsException e)
15. {
16. [Link]("ArrayIndexOutOfBounds Exception occurs");
17. }
18. catch(Exception e)
19. {
20. [Link]("Parent Exception occurs");
21. }
22. [Link]("rest of the code");
23. }
24.}
Test it Now
Output:
In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception
is pushed onto the stack.
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.
Page |05
[Link]
1. public class NestedTryBlock{
2. public static void main(String args[]){
3. //outer try block
4. try{
5. //inner try block 1
6. try{
7. [Link]("going to divide by 0");
8. int b =39/0;
9. }
10. //catch block of inner try block 1
11. catch(ArithmeticException e)
12. {
13. [Link](e);
14. }
15. //inner try block 2
16. try{
17. int a[]=new int[5];
18. //assigning the value out of array bounds
19. a[5]=4;
20. }
21. //catch block of inner try block 2
22. catch(ArrayIndexOutOfBoundsException e)
23. {
24. [Link](e);
25. }
26. [Link]("other statement");
27. }
28. //catch block of outer try block
29. catch(Exception e)
30. {
31. [Link]("handled the exception (outer catch)");
32. }
33. [Link]("normal flow..");
34. }
35.}
Output:
Page |05
Java finally block
Java finally block is a block used to execute important code such as closing the
connection, [Link] finally block is always executed whether an exception is handled or
not. Therefore, it contains all the necessary statements that need to be printed
regardless of the exception occurs or not.
o finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
o The important statements to be printed can be placed in the finally block.
o
o public class TestFinallyBlock1{
o public static void main(String args[]){
o
o try {
o
o [Link]("Inside the try block");
o
o //below code throws divide by zero exception
o int data=25/0;
o [Link](data);
o }
o //cannot handle Arithmetic type exception
o //can only accept Null Pointer type exception
o catch(NullPointerException e){
o [Link](e);
o }
o
o //executes regardless of exception occured or not
o finally {
o [Link]("finally block is always executed");
Page |05
o }
o
o [Link]("rest of the code...");
o
o }
o }
Outp
[Link]
Page |05
21. [Link]("finally block is always executed");
22. }
23.
24. [Link]("rest of the code...");
25. }
26. }
Output:
We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related to
user inputs, servers, etc.
We can also define our own set of conditions and throw an exception explicitly using the
throw keyword. For example, we can throw an ArithmeticException if we divide a
number by another number. Here, we just need to set the condition and throw the
exception using the throw keyword i.e., for user defined exceptions.
Page |05
Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the subclass of Throwable and the user-defined exceptions usually extend
the Exception class.
In this example, we have created a method named validate() that accepts an integer as a
parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.
[Link]
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.
Output:
Page |05
1. public class TestThrow {
2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate square
");
6. }
7. else {
8. [Link]("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. [Link](-3);
15. [Link]("Rest of the code..");
16. }
17.}
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to
provide the exception handling code so that the normal flow of the program can be
maintained.
Page |05
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is the programmer's fault that he
is not checking the code before it is used.
Let's see the example of Java throws clause which describes that checked exceptions
can be propagated by throws keyword.
[Link]
1. import [Link];
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{ m(); }
7. void p(){
8. try{
9. n();
10. }catch(Exception e){[Link]("exception handled");}
11. }
12. public static void main(String args[]){
13. Testthrows1 obj=new Testthrows1();
14. obj.p();
15. [Link]("normal flow...");
16. }
17.}
Test it Now
Output:
exception handled
normal flow...
[Link]
Page |05
1. import [Link].*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. [Link]();
12. }catch(Exception e){[Link]("exception handled");
13.}
14. [Link]("normal flow...");
15. }
16.}
Test it Now
Output:
exception handled
normal flow...
Page |05
4. throw is used within the method. throws is used with the method
signature.
5. We are allowed to throw only one We can declare multiple exceptions
exception at a time i.e. we cannot using throws keyword that can be
throw multiple exceptions. thrown by the method. For example,
main() throws IOException,
SQLException.
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
Page |05
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:
20. }
21. else {
22. [Link]("welcome to vote");
23. }
24. }
25.
26. // main method
27. public static void main(String args[])
28. {
29. try
30. {
31. // calling the method
32. validate(13);
33. }
34. catch (InvalidAgeException ex)
35. {
36. [Link]("Caught the exception");
37.
38. // printing the message from InvalidAgeException object
Output:
Page |05
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
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.
Process Thread
Page |05
A process is an instance of a program Thread is a segment of a process or a
that is being executed or processed. lightweight process that is managed by the
scheduler independently.
Each process is treated as a new The operating system takes all the user-level
process by the operating system. threads as a single process.
If one process gets blocked by the If any user-level thread gets blocked, all of its
operating system, then the other peer threads also get blocked because OS
process can continue the execution. takes all of them as a single process.
Context switching between two Context switching between the threads is fast
processes takes much time as they are because they are very lightweight.
heavy compared to thread.
The data segment and code segment Threads share data segment and code
of each process are independent of the segment with their peer threads; hence are
other. the same for other threads also.
The operating system takes more time Threads can be terminated in very little time.
to terminate a process.
Multithreading:
Multithreading is a process of executing multiple threads simultaneously.
Page |05
3. Running
4. Blocked (Non-runnable state)
5. Dead
Page |05
1. New (Newborn State): When we create a thread object using Thread class, thread
is born and is known to be in Newborn state. That is, when a thread is born, it
enters into new state but the start() method has not been called yet on the
instance.
2. Runnable state: Runnable state means a thread is ready for execution. When the
start() method is called on a new thread, thread enters into a runnable state.
In runnable state, thread is ready for execution and is waiting for availability of
the processor (CPU time). That is, thread has joined queue (line) of threads that
are waiting for execution.
If all threads have equal priority, CPU allocates time slots for thread execution on the
basis of first-come, first-serve manner. The process of allocating time to threads is
known as time slicing. A thread can come into runnable state from running, waiting,
or new states.
3. Running state: Running means Processor (CPU) has allocated time slot to
thread for its execution. When thread scheduler selects a thread from the
runnable state for execution, it goes into running state.
In running state, processor gives its time to the thread for execution and executes
its run method. This is the state where thread performs its actual functions. A
thread can come into running state only from runnable state.
A running thread may give up its control in any one of the following situations and
can enter into the blocked state
a) When the sleep() method is invoked on a thread to sleep for the specified time
period, the thread is out of the queue during this period. The thread again reenters into
the runnable state as soon as this period is elapsed.
b) When a thread is suspended using the suspend() method for some time to satisfy
some conditions. A suspended thread can be revived by using resume() method.
c) When the wait() method is called on a thread to wait for some time. The thread in the
wait state can be re-run using notify() or notifyAll() method.
4. . Blocked state: A thread is considered to be blocked when it is suspended, sleeping,
or waiting for some time to satisfy some condition.
5. Dead state: A thread dies or moves into dead state automatically when its run()
method completes the execution of statements. That is, a thread is terminated or dead
when a thread comes out of run() method. A thread can also be dead when the stop()
method is called.
During the life cycle of thread in Java, a thread moves from one state to another state in
a variety of ways. This is because in multithreading environment, when multiple threads
are executing, only one thread can use CPU at a time. Page |
326
All other threads live in some other states, either waiting for their turn on CPU or
waiting for satisfying some conditions. Therefore, a thread is always in any of the five
states.
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
Output:
Current Thread: Thread[main,5,main]
Page |
327
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.
The Thread Class:
Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and implements Runnable
interface.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
15. ld(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
16. public void suspend(): is used to suspend the thread(depricated).
17. public void resume(): i8s used to resume the suspended thread(depricated).
18. public void stop(): is used to stop the thread(depricated).
Page |
328
The Runnable Interface
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface have only
one method named run().
public void run( ): is used to perform action for a thread.
Creating Threads:
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Output:
thread is running...
FileName: [Link]
Output:
thread is running...
Programs
Write a Java Program that creates a thread with a specified name, and print the
name and id of the thread.
Program:
Sleep()
thread Class is a class that is basically a thread of execution of the programs. It is
present in [Link] package. Thread class contains the Sleep() method. There are two
overloaded methods of Sleep() method present in Thread Class, one is with one
argument and another one is with two arguments. The sleep() method is used to stop
the execution of the current thread(whichever might be executing in the system) for a
specific duration of the time and after that time duration gets over, the thread which
is executing earlier starts to execute again.
Program:
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:
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](getName() + ": " + i);
try {
[Link](500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}
Output:
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5
Thread priorities:
Each thread has a priority. Priorities are represented by a number between 1 and 10. In
most cases, the thread scheduler schedules the threads according to their priority
Page |
332
(known as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses. Note that not only JVM a Java
programmer can also assign the priorities of a thread explicitly in a Java program.
Let's discuss the setter and getter method of the thread priority.
FileName: [Link]
Output:
Page |
335
Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads
to any shared resource.
Java Synchronization is better option where we want to allow only one
thread to access the shared resource.
Synchronization in Java is the process that allows only one thread at a particular
time to complete a given task entirely.
By default, the JVM gives control to all the threads present in the system to
access the shared resource, due to which the system approaches race condition.
Synchronization is built around an internal entity known as the lock or monitor. Every
object has an 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.
From Java 5 the package [Link] contains several lock
implementations.
Page |
436
In the above code, as you can see, both the statements are running simultaneously,
which creates an inconsistency in the program. Just using the synchronized keyword
Page |
437
before the method can easily solve this problem, as shown below.
Thread Synchronization:
There are two types of thread synchronization mutual exclusive and inter-
thread communication.
1. Mutual Exclusive
2. Cooperation (Inter-thread communication)
Page |
438
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:
[Link] Method
[Link] 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( ) { }
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
}
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{ }
CPU idle time is a procedure that prevents CPU cycles from being wasted. When many
threads are running at the same time, they may need to communicate with one another
by sharing information. A thread exchanges data before or after changing its state.
Communication between threads is vital in a variety of cases.
Page |
439
For example; Assume there are two threads: A and B. Thread B executes its task using
the data developed by Thread A. Thread B would waste several CPU cycles while it waits
for Thread A to create data. On the other hand, threads A and B do not have to wait and
check each other's status every time they complete their tasks if they engage with each
other after they have finished their tasks, As a result, you would not waste CPU cycles
[Link] is implemented by following methods of Object class:
[Link]( )
[Link]( )
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 It waits until object is notified.
InterruptedException
public final void wait(long timeout)throws It waits for the specified
InterruptedException 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( )
Page |
440
Understanding the process of inter-thread communication:
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 The sleep() method doesn't
lock. 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 notifiedby notify() or After the specified amount of
notifyAll() methods time, sleep is
completed
Page |
441