0% found this document useful (0 votes)
45 views13 pages

Java Unit-3

The document discusses exception handling in Java. It defines exceptions as unexpected or abnormal situations that occur at runtime. There are three main types of exceptions in Java: checked exceptions, unchecked exceptions, and errors. Checked exceptions must be declared and handled, while unchecked exceptions do not need to be declared but can be caught. Errors are usually fatal and unrecoverable. The document also discusses the keywords used for exception handling in Java like try, catch, throw, throws, and finally and provides examples of their usage. Finally, it discusses multi-threading in Java, defining a thread as a lightweight sub-process and explaining how multi-threading allows for concurrent execution of multiple threads to maximize CPU utilization.

Uploaded by

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

Java Unit-3

The document discusses exception handling in Java. It defines exceptions as unexpected or abnormal situations that occur at runtime. There are three main types of exceptions in Java: checked exceptions, unchecked exceptions, and errors. Checked exceptions must be declared and handled, while unchecked exceptions do not need to be declared but can be caught. Errors are usually fatal and unrecoverable. The document also discusses the keywords used for exception handling in Java like try, catch, throw, throws, and finally and provides examples of their usage. Finally, it discusses multi-threading in Java, defining a thread as a lightweight sub-process and explaining how multi-threading allows for concurrent execution of multiple threads to maximize CPU utilization.

Uploaded by

Simran fatima
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit – III

1. Exception handling in JAVA

Exception:

 An exception is an unexpected or abnormal or unwanted situation that occur at runtime


is called as Exception.
 Exception can also be said as the runtime error.
 In JAVA, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
 The Exception Handling in JAVA is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained. Through exception
handling we can ensure the program is not terminated abnormally and user data is not
disturbed.
 Runtime errors can be deleted by JVM

 The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is
why we need to handle exceptions.

Types of Exceptions:

 There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, there are three types of exceptions
namely:

1. Checked Exception
2. Unchecked Exception
3. Error

1) Checked Exception

 The classes that directly inherit the Throwable class except Runtime Exception and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception

 The classes that inherit the Runtime Exception are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException,
etc. Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
3) Error

 Error is irrecoverable. Some example of errors are OutOfMemory Error, VirtualMachine


Error, Assertion Error etc.

Error vs Exception:
Basis of comparison Exception Error
Recoverable/ Exception can be recovered by An error cannot be recovered.
Irrecoverable using the try-catch block.

Type It can be classified into two All error in JAVA are unchecked.
categories i.e. checked and
unchecked
Occurrence It occurs at compile time or run It occurs at run time.
time
Package It belongs to java.lang.Exception It belongs to java.lang.Error package.
package
Known or Unknown Only checked exceptions are Errors will not be known to the compiler.
known to the compiler.
Causes It is mainly caused by the It is mostly caused by the environment in
application itself. which the application is running.
Example Checked Exception; java.lang.StackOverFlow,

SQL Exception. IO Exception java.lang.OutOfMemoryError.

Unchecked Exception:

ArrayIndexOutOfBound Exception,

NullPointer Exception,

Arithematic Exception.

JAVA Exception Keywords:

There are 5 keywords in JAVA. They are

 TRY:

 It is a keyword used to create block of statement which are doubtful of generating


exception

 SYNTAX:

Try
{
-------
-------
-------
}
//Example program :

Import java.lang.*;
class Execute
{
public static void main(String[] args)
{
int x=10;y=0;z;
try
{
z=x/y ; //divide by zero which is infinety
System.out.println(z);
}
catch(arthimeticexception e)
{
system.out.println(“division is not possible “);
}
system.out.println(“program over”);
}
}

CATCH:

: It is reserved keyword, which is used to handle the exception.

if there is an exception in try block then only catch block will be executed. If no exception in try
block, it doesn’t catch in catch block.

 SYNTAX:

Catch
{
-------
-------
-------
}

Try block should be immediately after try block

if there exception in try block then only catch block will executed

if exception doesn’t occur in try block, then it does not catch in catch block
THROW:

It is a keyword used to create an exception and throw it explicitly.

SYNTAX:
throw new exceptiontype(“content”);

>throw is a keyword

>and “new” is a operator

>and the exception type (ex arthithematic or array out of bound etc)

Example program for throw :

Import java.lang.*;

Class Robo

{
public static void main(String[] args);

{
try

{
throw new arthimeticException(“this is my own exception”);

System.out.println(“this is try block”);

}
catch(airtimeticException e)

{
System.out.println(e.getmessage());

}
System.out.println(“program over”);

}
output:
this is my own exception

Program over
THROWS:

It is a keyword used when we doesn’t want to handle the exception and try to send the exception to the
jvm or caller.

SYNTAX:

Return type method name ( parameters) throws exception list

_____________

_____________

Example program for throws:

Import java.lang.*;

Class Test

{
public static void main(String[] args)throws exception

{
Thread.sleep(2000);

//sleep is method which is used in thread class

System.out.println(“demo on throws”);

}
}
Explanation of the above program

>output will be in 2000miliseconds(i.e 2 secs). then thread will be in waiting state and prints
demo on throws

>we have to handle the sleep method during compilation time.

>if we don’t handle the sleep method it generates compile time error.

 FINALLY:
 The ‘finally’ block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
 It is the keyword used to create a block of code that will be executed after a try/catch
block whether the exception is handled or not.
 If exception occurs catch block executes and then finally block is executed.
 If no exception, then finally block will be executed.
 It should be written after try block or catch block.
//program for finally block
Import java.lang.*;
class Robo
{
public static void main(Sting args [])
{
try
{
Int x, y, res;
X=10;
Y=0;
res = x/y;
System.out.println(res);
}
catch(ArithematicException e)
{
System.out.println(“Division by zero is not possible ”);
}
finally
{
System.out.println(“Hi! This is final block”);
}
System.out.println(“Program ends”);
}

Difference Between Throw and Throws keywords:


S.No Throw Throws
1. The throw keyword is used to throw an The throws keyword is used in the method
exception explicitly in the code, inside the signature to declare an exception which
method or the block of code. might be thrown by the function while the
execution of the code.
2. Type of exception using throw keyword, we can only Using Throws keyword, we can declare both
propagate unchecked exception (i.e.) the checked checked and unchecked exceptions. However,
exception cannot be propagated using throw only. the throws keyword can be used to propagate
checked exceptions only.
3. The throw keyword is followed by an instance of The throws keyword is followed by class
Exception to be thrown. names of Exceptions to be thrown.
4. Throw is used within the method Throws is used with the method signature.
5. We are allowed to throw only one exception at a We can declare multiple exceptions using
time i.e. we cannot throw multiple exceptions. throws keyword that can be thrown by the
method. For example, main() throws
IOException, SQLException.
2. Multi-threading in JAVA
Thread and its life-cycle:

 A thread is a lightweight sub process. It separates path of execution because each


thread runs in a different stack frame. A process may contain multiple threads.
Threads share the process resources, but still, they execute independently.
 Multi-threading in JAVA is a process of executing two or more threads
simultaneously to maximum utilization of CPU.
 Multi-threaded applications execute two or more run concurrently.
 Hence, it is also known as Concurrency in JAVA.
 Each thread runs parallel to each other. Multiple threads don’t allocate separate
memory area, hence they save memory. Also, context switching between threads
takes less time.
 Multi-threading allows an application / program to be always reactive to input,
even already running with some background tasks.
 Multi-threading allows the faster execution of tasks, as threads executes
independently.
 Multi-threading provides better utilization of cache memory as threads share the
common resources.
 Multi-threading reduces the number of required server as one server can execute
multiple threads at a time.

Thread Life Cycle in JAVA

The life-cycle of thread:

Stages of life-cycle in JAVA:

There are various stages in life cycle of thread as shown in the figure.

1. New
2. Runnable
3. Running
4. Waiting
5. Dead

New: In this phase, the thread is created using class “Thread class”. It remains in
this state till the program starts the thread. It is known as born thread.

Runnable: In this page, the instance of the thread is invoked with a start method.
The thread control is given to scheduler to finish the execution. It depends on the
scheduler, whether to run the thread.

Running: When the thread starts executing, then the state is changed to
“running” state. The scheduler selects one thread from thread pool and it starts
executing in the application.

Waiting: This is the state when a thread has to wait. As the multiple threads are
running in the application, there is no need for synchronization between threads.
Hence, one thread has to wait till the other thread gets executed. Therefore, the
state is referred as waiting state.

Dead: This is the state when the thread is terminated. The thread is in running
state and as soon as it completed processing it is in “dead state”.

How to create Threads:

 In JAVA, a thread is a lightweight sub process. Every JAVA program executes by a


thread called main thread. When a JAVA program gets executed, the main thread
gets created automatically. All other threads are called from the main thread.
 The JAVA programming language provides two methods to create threads, and
they are listed below:
i. Using Thread class (by extending Thread class).
ii. Using Runnable interface (by implementing Runnable interface)

Extending JAVA Threads:

 The JAVA contains a built-in class Thread inside java.lang package. The Thread
contains all the methods that are related to threads.
 To create a thread using Thread class, follow the steps given below:
Step-1: Create a class as a child of Thread class. That means, create a class to
extend Thread class.
Step-2: Override the run () method with the code that is to be executed by thread.
The run () method must be public while overriding.
Step-3: Create the object of the newly created class in the main () method.
Step-4: Call the start () method on the object created in the above step.
Example:

class SampleThread extends Thread


{
public void run()
{
System.out.println(“Thread is under Running…”);
for(int i= 1, i<= 10, i++)
{
System.out.println(“i= “+1);
}
}
}
public class My_Thread_Test
{
public static void main(String[] args)
{
SampleThread t1 = new SampleThread();
System.out.println(“Thread about to start…”);
t1.start();
}
}
Output:
Thread about to start…
Thread is under Running…
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9

Synchronized keyword:
 The process of allowing only a single thread to access the shared data or resource at a
particular point of time is known as Synchronization.
 Need of synchronization.
 If the data is keep on updating by threads we should go for synchronization.
 We need synchronization keyword.
 Synchronization is applied on methods blocks
 We cant apply synchronization on variables and class.
 Synchronization is developed locking mechanism locking mechanism taken care by jvm.
 As Java is a multi-threaded language, it supports a very important concept of Synchronization.
 This method helps us to protect the data from the access by multiple threads.
 Java provides the mechanism of synchronization using the synchronized blocks.
 We declare all synchronized blocks in Java by using a synchronized keyword. A block that is
declared with a synchronized keyword ensures that only a single thread executes .

IMP POINTS:

 Synchronization is a technique through which we can control multiple thread or among the
number of threads only one thread will enter inside synchronisaton area the main purpose of
synchronization area.
 The main purpose of synchronization is to overcome the problem of multithreading when
threads are trying to access same resource
 By using synchronized keyword , only thread enter into the loop after its work done , the second
will enter and so on, synchronized keyword will limit the access of three threads entering into
loop.
 SYNCHRONISATION IS CLASSIFIED INTO :
 METHOD LEVEL SYNCHRONISATION AND BLOCK LEVEL SYNCHRONISATION.

>Method level synchronization:

Public void run()

________ code;

t1.start();

t2.start();

t3.start();

here t1,t2,t3 are trying to access same resource so these is waiting problem and three threads at a
time enter into the same resource,To avoid this problem we have to use synchronized keyword.

Public synchronized void run()

{
------some code------

T1.start();
T2.start();

T3.start();

Explaination of above program :

By using synchronized keyword,only one thread enter into the loop after its work done,the second
thread will enter and so on..

Synchronized keyword will limit the access of three threads entering into the loop.

..

//BLOCK LEVEL SYNCHRONISATION…..

Public void hotel();

Sychronisation(this)

{
//some code

t1.start();

t2.start.();

t3.start();

//here only synchronization is applicable for block of code.

 Syntax:

synchronized( lockObject )
{
// synchronized statements
}
How to Avoid Deadlock in Java
 In Java, deadlock is a part of multithreading. The multithreading environment allows us to run
multiple threads simultaneously for multitasking.
 Sometimes the threads find themselves in the waiting state, forever that is a deadlock situation.
 The deadlock is a situation when two or more threads try to access the same object that is acquired
by another thread. Since the threads wait for releasing the object, the condition is known as
deadlock.The situation arises with more than two threads.

What is Deadlock :
 In the thread, each object has a lock. To acquire a lock, Java provides synchronization to lock a method or
code block. It allows that at a time only one thread can access that method.
 Nevertheless, if a thread wants to execute a synchronized method it first tries to acquire a lock. It is
possible that another thread has already acquired that lock then the thread (that wants to acquire the lock)
will have to wait until the previous thread does not release the lock.
 Let’s understand this with an example;
Suppose, there are two threads A and B. The thread A and B acquired the lock of Object-A and Object-
B, respectively. Assume that thread A executing method A and wants to acquire the lock on Object-B,
while thread B is already acquired a lock on Object-B.

On the other hand, thread B also tries to acquire a lock on Object-A, while thread A is acquired a lock
on Object-A. In such a situation both threads will not complete their execution and wait for releasing
the lock. The situation is known as, deadlock.

//program for deadlock

Public void methodA()


{
//...
synchronized(lockA)
{
//...
synchronized(lockB)
{
//...
}
}
}
publicvoidmethodB()
{
//...
synchronized(lockB)
{
//...
synchronized(lockA)
{
//...
}
}
}
How to detect deadlock in Java?
 There are following ways to detect a deadlock:

o First, we look and understand the code if we found nested synchronized block or trying to get a lock
on a different object or calling a synchronized method from other synchronized method, these reason
leads to a deadlock situation.
o Another way to detect deadlock is to use the io portal. It allows us to upload a thread dump and
analyze it.
o We can also use jConsole or VisualVM to detect deadlock. It shows us which threads are getting
locked and on which object.

 In the above example, there are two threads that are attempting to transfer money to each other at the
same time. It creates a deadlock situation because the threads try to acquire the lock in the reverse order.

How to avoid deadlock in Java?


Although it is not possible to avoid deadlock condition but we can avoid it by using the following ways:

o Avoid Unnecessary Locks: We should use locks only for those members on which it is required.
Unnecessary use of locks leads to a deadlock situation. We recommend you to use a lock-free data
structure. If possible, keep your code free form locks. For example, instead of using synchronized
ArrayList use the ConcurrentLinkedQueue.
o Avoid Nested Locks: Another way to avoid deadlock is to avoid giving a lock to multiple threads if we
have already provided a lock to one thread. Since we must avoid allocating a lock to multiple threads.
o Using Thread.join() Method: You can get a deadlock if two threads are waiting for each other to
finish indefinitely using thread join. If your thread has to wait for another thread to finish, it's always
best to use join with the maximum time you want to wait for the thread to finish.
o Use Lock Ordering: Always assign a numeric value to each lock. Before acquiring the lock with a
higher numeric value, acquire the locks with a lower numeric value.
o Lock Time-out: We can also specify the time for a thread to acquire a lock. If a thread does not
acquire a lock, the thread must wait for a specific time before retrying to acquire a lock.

You might also like