0% found this document useful (0 votes)
2 views24 pages

Java Prograaming - Notes (Unit-4)

Uploaded by

adityavpawal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

Java Prograaming - Notes (Unit-4)

Uploaded by

adityavpawal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-4 EXCEPTION HANDLING & MULTITHREADING

1.​ TYPES OF ERRORS & EXCEPTIONS


errors and exceptions are both types of throwable objects, but they represent different types of problems
that can occur during the execution of a program.

Errors are usually caused by serious problems that are outside the control of the program, such as
running out of memory or a system crash. Errors are represented by the Error class and its subclasses. Some
common examples of errors in Java include:
●​ OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) runs​ out
of memory.
●​ StackOverflowError: Thrown when the call stack overflows due to too many method
invocations.
●​NoClassDefFoundError: Thrown when a required class cannot be found.

Since errors are generally caused by problems that cannot be recovered from, it’s usually not
appropriate for a program to catch errors. Instead, the best course of action is usually to log the error and exit
the program.
Exceptions are used to handle errors that can be recovered from within the program. Exceptions are
represented by the Exception class and its subclasses. Some common examples of exceptions in Java include:
●​NullPointerException: Thrown when a null reference is accessed.
●​ IllegalArgumentException: Thrown when an illegal argument is passed to a method.
●​IOException: Thrown when an I/O operation fails.

1
Exceptions are the conditions that occur at runtime and may cause the termination of the program.
But they are recoverable using try, catch and throw keywords. Exceptions are divided into two categories:
●​ Checked exceptions
Checked exceptions are also known as compile-time exceptions as these exceptions are
checked by the compiler during the compilation process to confirm whether the exception is
handled by the programmer or not. If not, then the system displays a compilation error.
For
example, SQLException, IOException, InvocationTargetException, a nd​
ClassNotFoundException.
●​ Unchecked exceptions
The unchecked exceptions are those exceptions that occur during the execution of the
program. Hence they are also referred to as Runtime exceptions. These exceptions are
generally ignored during the compilation process. They are not checked while compiling the
program.
For example, programming bugs like logical errors, and using incorrect APIs
Checked exceptions like IOException known to the compiler at compile time while​ unchecked
exceptions like ArrayIndexOutOfBoundException known to the compiler at runtime. It is mostly caused
by the program written by the programmer.

2
Errors Exceptions

We can recover from exceptions by either using try-catch


Recovering from Error is not possible. block or throwing exceptions back to the caller.

Exceptions include both checked as well as unchecked type.


All errors in java are unchecked type.

Errors are mostly caused by the environment in


Program itself is responsible for causing exceptions.
which program is running.

Errors can occur at compile time as well as


run time. Compile Time: eg Syntax Error All exceptions occurs at runtime but checked exceptions are
known to the compiler while unchecked are not.
Run Time: Logical Error.

They are defined in [Link] package.


They are defined in [Link] package

Examples : Checked Exceptions : SQLException, IOException


Examples : [Link],
Unchecked Exceptions : ArrayIndexOutOfBoundException,
[Link]
NullPointerException, ArithmeticException.

2.​ TRY & CATCH STATEMENT


The try...catch block in Java is used to handle exceptions and prevents the abnormal termination of
the program.
Syntax:

The try block includes the code that might generate an exception.
The catch block includes the code that is executed when there occurs an exception inside the try
block.

3
class TryDemo {
public static void main(String[] args) { try { ArithmeticException
int divideByZero = 5 / 0; [Link]("Rest of code in => / by zero
try block");
}
catch (ArithmeticException e) {
[Link]("ArithmeticException => "
+[Link]());
}
}}

class Main {
public static void main(String[] args) { try { Finally block is always
int divideByZero = 5 / 0; executed
} Exception in thread "main"
finally { [Link]:
[Link]("Finally block is always executed"); / by zero​ at
} [Link]([Link])
}
}

try...catch...finally block

we can also use the finally block after the try...catch block.
import [Link].*; class
ListOfNumbers { Entering try statement Exception =>
private int[] list = {5, 6, 8, 9, 2}; public void Index 5 out of bounds for length 5
writeList() { Closing PrintWriter
PrintWriter out = null; try {
[Link]("Entering try statement"); out = new
PrintWriter(new
FileWriter("[Link]")); for (int i
= 0; i < 7; i++)
{​ [Link]("Value at: " + i + " = " +

4
list[i]);​ }

5
}
catch (Exception e)
{ [Link]("Exception => " +
[Link]());​ }
finally {
if (out != null)
{​ [Link]("Closing
PrintWriter");
[Link]();
}
else
{​ [Link]("PrintWriter not open");
​ }
} }}
class Main {
public static void main(String[] args) { ListOfNumbers list =
new ListOfNumbers(); [Link]();
}
}

3.​ NESTED TRY STATEMENTS

6
c

4.​ THROWS & THROW STATEMENTS


We use the throws keyword in the method declaration to declare the type of exceptions that might occur
within it.

import [Link].*; class


Main { [Link]:
public static void findFile() throws IOException { File [Link] (No such file or directory)
newFile=new File("[Link]"); FileInputStream stream=new
FileInputStream(newFile);
}
public static void main(String[] args) { try{
findFile();
} catch(IOException e) {
[Link](e);​ }
}
}

7
Throwing multiple exceptions​

8
5.​ BUILT-IN EXCEPTIONS
The Java programming language has several built-in exception class that support exception handling.
All the built-in exception classes in Java were defined a package [Link].
S.
No. Checked Exception Class with Description

1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the
specified class cannot be found in the classpath.

2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an
object, but that the object's class does not implement the Cloneable interface.

3 InstantiationException
It is thrown when an application tries to create an instance of a class using the
newInstance method in class Class , but the specified class object cannot be
instantiated because it is an interface or is an abstract class.

4 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.

9
10
S.
No. Checked Exception Class with Description

5 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at
compile time, a NoSuchMethodException occurs during reflection when we try to
access a method that does not exist.

Unchecked Exception Class with Description

1.​ ArithmeticException​ It handles the arithmetic exceptions like dividion by zero


2.​ ArrayIndexOutOfBoundsException
It handles the situations like 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.​ ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of object into
an array of objects
4.​ ClassCastException​ It handles the situation when we try to improperly cast a class from one
type to another.
5.​ IllegalArgumentException This exception is thrown in order to indicate that a method has been
passed an illegal or inappropriate argument.
IllegalStateException​ It signals that a method has been invoked at an illegal or inappropriate
time.
6.​ IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify the state of the
thread when it is illegal.
7.​ IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an array , vector , string ,
and so forth.
8.​ NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
9.​ NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
10.​ NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer, but the format of
the input string is not appropriate or illegal.
11.​ StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either negative, or
greater than the size of the string itself.

11
6.​ 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. Chained Exception is used in such type of
situations.
// Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
public static void main(String[] args)
{
try{
NumberFormatException ex = new NumberFormatException("Exception"); [Link](new
NullPointerException( "This is actual cause of the
exception")); throw ex;
}catch(NumberFormatException ex) {
[Link](ex); [Link]([Link]());
}
}
}

Output:
[Link]: Exception [Link]: This is actual
cause of the exception

getCause():- This method returns actual cause of an exception. initCause(Throwable cause) :- This
method sets the cause for the calling exception.

7.​ CREATING OWN EXCEPTIONS (THROW CLAUSE)


Java provides us the facility to create our own exceptions which are basically derived classes of
Exception.
Creating our own Exception is known as a custom exception or user-defined exception. Basically, Java
custom exceptions are used to customize the exception according to user needs.
In simple words, we can say that a User-Defined Exception or custom exception is creating your
own exception class and throwing that exception using the ‘throw’ keyword.

12
8.​ CREATING THREAD BY EXTENDING TO THREAD CLASS
Used to maximize the CPU utilization.
We don't want our CPU to be in a free state; for example, Func1() comes into the memory and
demands any input/output process. The CPU will need to wait for unit Func1() to complete its input/output
operation in such a condition. But, while Func1() completes its I/O operation, the CPU is free and not
executing any thread. So, the efficiency of the CPU is decreased in the absence of multithreading.

13
To create a thread using the thread class, we need to extend the thread class. The code you want to
execute on the thread's execution goes inside the run() method.

In order to execute the thread, the start() method is used. start() is called on the object of the
MyThread class. It automatically calls the run() method.

9.​ CREATING THREAD BY IMPLELENTING RUNNABLE INTERFACE


Steps To Create A Java Thread Using Runnable Interface:
●​ Create a class and implement the Runnable interface by using the implements
keyword.
●​ Override the run() method inside the implementer class.
●​ Create an object of the implementer class in the main() method.
●​ Instantiate the Thread class and pass the object to the Thread constructor.
●​ Call start() on the thread. start()will call the run()method.

14
Runnable Interface Vs Extending Thread Class
The Runnable interface is preferred over extending the Thread class because of the following
reasons:
●​ ​ As multiple inheritance is not supported in Java, it is impossible to extend the Thread class if
your class had already extended some other class.
●​ While implementing Runnable, we do not modify or change the thread's behavior.
●​ More memory is required while extending the Thread class because each thread creates a
unique object.
●​ Less memory is required while implementing Runnable because multiple threads share the
same object.

10.​ LIFE CYCLE OF THREAD


Basically state transitions of a thread that starts from its birth and ends on its death.
When an instance of a thread is created and is executed by calling start() method of Thread class, the
thread goes into runnable state.
When sleep() or wait() method is called by Thread class, the thread enters into non-runnable state.
From non-runnable state, thread comes back to runnable state and continues execution of statements.
When the thread comes out of run() method, it dies. These state transitions of a thread are called Thread
life cycle in Java..

A thread is a path of execution in a program that enters any one of the following five states during its
life cycle. The five states are as follows:
1.​ New
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.

15
Thread object exists but it cannot execute any statement because it is not an execution of
thread. Only start() method can be called on a new thread; otherwise, an
IllegalThreadStateException will be thrown.
2.​ Runnable
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).
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.
3.​ Running
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.
4.​ Blocked (Non-runnable state)
A thread is considered to be in the blocked state when it is suspended, sleeping, or waiting for
some time in order to satisfy some condition.
5.​ Dead
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.
11.​ THREAD EXCEPTIONS
When we call a sleep() method in a Java program, it must be enclosed in try block and
followed by catch block.
This is because sleep() method throws an exception named InterruptedException that
should be caught. If we fail to catch this exception, the program will not compile.
For example, a thread that is in a sleeping state cannot deal with the resume() method
because a sleeping thread cannot accept instructions. The same thing is true for the suspend() method
when it is used on a blocked thread.

16
12.​ THREAD PRIORITY & METHODS
●​ A thread's priority is an integer in the range 1 to 10.
●​ The larger the integer, the higher the priority.
●​ The thread scheduler uses this integer from each thread to determine which one should be
allowed to execute.

●​ Minimum priority
●​ Normal priority
●​ Maximum priority

The Thread class defines these priority types as


constants MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY, with values 1, 5, and 10,
respectively. NORM_PRIORITY is the default priority for a
new Thread.
●​ The setPriority() method of thread class is used to change the thread's priority.
●​ The getPriority() instance method returns the integer that represents its priority.

13.​ SYNCHRONIZATIONS
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
In the Multithreading concept, multiple threads try to access the shared resources at a time to
produce inconsistent results.
The synchronization is necessary for reliable communication between threads.
●​ Synchronization helps in preventing thread interference.

17
●​ Synchronization helps to prevent concurrency problems.
Synchronization is classified into two types
●​ Process Synchronization
The process is nothing but a program under execution. It runs independently isolated from
another process. The resources like memory and CPU time, etc. are allocated to the process by the
operation System.
●​ Thread Synchronization
Thread synchronization is two types, they are:
1.​ Mutual Exclusive:
A Mutex or Mutual Exclusive helps only one thread to access the shared
resources. It won’t allow the accessing of shared resources at a time. It can be achieved
in the following ways.
1.​ Synchronized Method
If we use the Synchronized keywords in any method then that method is
Synchronized Method.
●​It is used to lock an object for any shared resources.
●​The object gets the lock when the synchronized method is called.
●​The lock won’t be released until the thread completes its function.

18
2.​ Synchronized block
Suppose you don’t want to synchronize the entire method, you want to synchronize few lines
of code in the method, then a synchronized block helps to synchronize those few lines of code. It
will take the object as a parameter. It will work the same as Synchronized Method. In the case of
synchronized method lock accessed is on the method but in the case of synchronized block lock
accessed is on the object.

19
Static Synchronization
In java, every object has a single lock (monitor) associated with it. The thread which is
entering into synchronized method or synchronized block will get that lock, all other threads which
are remaining to use the shared resources have to wait for the completion of the first thread and
release of the lock.
Suppose in the case of where we have more than one object, in this case, two separate threads
will acquire the locks and enter into a synchronized block or synchronized method with a separate
lock for each object at the same time. To avoid this, we will use static synchronization.
In this, we will place synchronized keywords before the static method. In static synchronization,
lock access is on the class not on object and Method.

2.​ Cooperation (Inter Thread Communication in java)

14.​ INTER-THREAD COMMUNICATION


a technique through which multiple threads communicate with each other.
It provides an efficient way through which more than one thread communicates with each
other by reducing CPU idle time. CPU idle time is a process in which CPU cycles are not wasted.
When more than one threads are executing simultaneously, sometimes they need to
communicate with each other by exchanging information with each other. A thread exchanges
information before or after it changes its state.
For example, suppose that there are two threads A and B. Thread B uses data produced by
Thread A and performs its task.
If Thread B waits for Thread A to produce data, it will waste many CPU cycles. But if
threads A and B communicate with each other when they have completed their tasks, they do not
have to wait and check each other’s status every time.
Thus, CPU cycles will not waste. This type of information exchanging between threads is
called inter-thread communication in Java.

20
Inter thread communication in Java can be achieved by using three methods provided by Object class of
[Link] package. They are:
1.​ wait()
2.​ notify()
3.​ notifyAll()
These methods can be called only from within a synchronized method or synchronized block of code
otherwise, an exception
named IllegalMonitorStateException is thrown.
***All these methods are declared as final. Since it throws a checked exception,
therefore, you must be used these methods within Java try-catch block
wait()
wait() method in Java notifies the current thread to give up the monitor (lock) and to go into
sleep state until another thread wakes it up by calling notify() method.
This method throws InterruptedException.
Syntax: public final void wait()
public final void wait(long millisecond) throws InterruptedException
notify()
The notify() method wakes up a single thread that called wait() method on the same object.
If more than one thread is waiting, this method will awake one of them.
Syntax: public final void notify()
notifyAll()
The notifyAll() method is used to wake up all threads that called wait() method on the same
object. The thread having the highest priority will run first. Syntax: public final void notifyAll()
Producer-Consumer Problem in Java using wait and notify methods
●​ Q where we will try to synchronize data.
●​ Producer where Producer thread will produce data (or some goods).
●​ Consumer where Consumer thread will wait for Producer to produce data. When the Producer
thread completes the production of data, the Consumer thread will take that data and use it.

15.​ DEADLOCK
Deadlock in java is a programming situation where two or more threads are blocked forever.
Java deadlock situation arises with at least two threads and two or more resources.
Deadlock describes a situation where two or more threads are blocked forever, waiting for each
other. Deadlock occurs when multiple threads need the same locks but obtain them in different order.
A Java multithreaded program may suffer from the deadlock condition because the synchronized
keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the
specified object.

21
public class TestThread
{
public static Object Lock1 = new Object(); public static
Object Lock2 = new Object();

public static void main(String args[]) { ThreadDemo1 T1 =


new ThreadDemo1(); ThreadDemo2 T2 = new
ThreadDemo2(); [Link]();
[Link]();
}
private static class ThreadDemo1 extends Thread { public void run() {
synchronized (Lock1) {
[Link]("Thread 1: Holding lock 1...");
try { [Link](10); } catch (InterruptedException e) {}
[Link]("Thread 1: Waiting for lock 2...");
synchronized (Lock2) { [Link]("Thread 1: Holding lock 1 & 2...");​ }
​ }​ }​ }
private static class ThreadDemo2 extends Thread { public void run() {
synchronized (Lock2) {​ [Link]("Thread 2: Holding lock 2..."); try {
[Link](10); }​ catch (InterruptedException e) {} [Link]("Thread
2: Waiting for lock 1...");
synchronized (Lock1) {​ [Link]("Thread 2: Holding lock 1&2...");
}​ }​ }​ }}

Thread 1: Holding lock 1...


Thread 2: Holding lock 2...
Thread 2: Waiting for lock 1...
Thread 1: Waiting for lock 2...
Deadlock Solution

22
public class TestThread {
public static Object Lock1 = new Object(); public static
Object Lock2 = new Object(); public static void
main(String args[]) {
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
[Link]();
[Link]();
}
private static class ThreadDemo1 extends Thread { public void run() {
synchronized (Lock1) {​ [Link]("Thread 1: Holding lock 1...");
try { [Link](10); }catch (InterruptedException e) {}

23
[Link]("Thread 1: Waiting for lock 2...");
synchronized (Lock2) { [Link]("Thread 1: Holding lock 1 & 2...");
}​ }​ }​ }
private static class ThreadDemo2 extends Thread { public void run() {
synchronized (Lock1) { [Link]("Thread 2: Holding
lock 1...");
try {​ [Link](10);​ } catch (InterruptedException e) {}
[Link]("Thread 2: Waiting for lock 2...");
synchronized (Lock2) { [Link]("Thread 2: Holding lock 1 & 2...");
}​ }​ }​ }​ }

Thread 1: Holding lock 1...


Thread 1: Waiting for lock 2...
Thread 1: Holding lock 1 & 2...
Thread 2: Holding lock 1...
Thread 2: Waiting for lock 2...
Thread 2: Holding lock 1 & 2...

24

You might also like