0% found this document useful (0 votes)
23 views34 pages

Unit 04 Java

Uploaded by

Harish Khojare
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
23 views34 pages

Unit 04 Java

Uploaded by

Harish Khojare
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 34

Unit 04 Exception Handling and Multithreading

Exception is an abnormal condition that arises when executing a program.


In the languages that do not support exception handling, errors must be checked and handled
manually, usually through the use of error codes.

In contrast, Java:
► Provides syntactic mechanisms to signal, detect and handle errors.
► Ensures a clean separation between the code executed in the absence of errors and the code to
handle various kinds of errors.
► Brings run-time error management into object-oriented programming.
An exception is an object that describes an exceptional condition (error) that has occurred when
executing a program.
Exception handling involves the following:
1) when an error occurs, an object (exception) representing this error is created and thrown in the
method that caused it
2) that method may choose to handle the exception itself or pass it on
3) either way, at some point, the exception is caught and processed
When and how it happens

An exception can occurs for many different reasons


 A user has entered invalid data.
 A file that need to be opened cannot be found.
 A network connection has been lost in the middle of the communication or the JVM has run out of
the memory.

Java Exception handles as follow


 Find the problem (Hit the exception)
 Inform that an error has occurred ( throw the Exception)
 Receive the error information(Catch the exception)
 Take corrective action ( Handle the Exception)
Hierarchy of Java Exception classes
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked.
An error is considered as the unchecked exception.
According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions

1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-
time.

2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords

Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone. It can be
followed by finally block later.
finally The "finally" block is used to execute the important code of the program.
It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an
exception. It specifies that there may occur an exception in the method.
It is always used with method signature.
Java try-catch block
Java try block

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 of try block, the rest of the block code will not
execute. So, it is recommended not to keeping the code in try block that will not throw an
exception.Java try block must be followed by either catch or finally block.

Syntax of Java try-catch:

try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

Java catch block


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., Exception) or the
generated exception type.
Problem without exception handling

public class TryCatchExample1


{
public static void main(String[] args)
{
int data=50/0; //may throw exception

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

}
}

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

Note: As displayed in the above example, the rest of the code is not executed.
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Solution by exception handling

public class TryCatchExample2 {


public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

Output:
java.lang.ArithmeticException: / by zero
rest of the code
Java Nested try block
The try block within a try block is known as nested try block in java.

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.

Syntax:
try
{
statement ;
try
{
statement ;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Java Multi-catch block
 A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler.
 At a time only one exception occurs 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.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
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"); }
System.out.println("rest of the code"); } }
Java finally block

Java finally block is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block follows try or catch block.


Java finally block

public class TestFinallyBlock2{


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..."); Output:Exception in thread main
} java.lang.ArithmeticException:/ by zero
finally block is always executed
} rest of the code...
Java throw exception
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or unchecked exception in java by throw keyword. The throw keyword is
mainly used to throw custom exception.
The syntax of java throw keyword is given below.
throw new exception;

Example:
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Java throws keyword
 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 normal flow can be maintained.
 Exception Handling is mainly used to handle the checked exceptions.
 If there occurs any unchecked exception such as NullPointerException, it is programmers fault
that he is not performing check up before the code being used.

Syntax of java throws


return_type method_name() throws exception_class_name{
//method code
}

Which exception should be declared


Ans) checked exception only, because:
unchecked Exception: under your control so correct your code.
error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError
or StackOverflowError.
Java throws example
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();

System.out.println("normal flow...");
} }
Difference between throw and throws in Java

No. throw throws


1) Java throw keyword is used to Java throws keyword is used to
explicitly throw an exception. declare an exception.

2) Checked exception cannot be Checked exception can be


propagated using throw only. propagated with 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.
5) You cannot throw multiple You can declare multiple exceptions
exceptions. e.g.
public void method()throws
IOException,SQLException.
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple operations
at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

A thread is a:
► Facility to allow multiple activities within a single process
► Referred as lightweight process
► A thread is a series of executed statements
► Each thread has its own program counter, stack and local variables
► A thread is a nested sequence of method calls
► Its shares memory, files and per-process state
Life cycle of a Thread
A thread can be in one of the five states
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
Start()

Run method
Life cycle of a Thread

1. New
A newly created thread object instance on which the start() method has not yet been invoked(not yet
started execution) is in the new state.
2. Runnable A thread in New state enters the Runnable state when the start() method is invoked on
it.
There are 2 important points to note regarding the runnable state – ► When the thread enters the
runnable state after invoking the start() method, it is not necessary that the thread immediately
starts executing. A thread runs when the logic it holds in its method can be executed by the
processor. In case the thread logic needs any resource which is not available then the thread waits
for the resource to become available. ► A thread in runnable state may run for some time and then
get blocked or may enter the waiting or timed waiting states.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
How to create thread

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

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:


3. Thread()
4. Thread(String name)
5. Thread(Runnable r)
6. Thread(Runnable r,String name)
Java Thread Example by extending Thread class

class Multi extends Thread{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

Output:thread is running...
Java Thread Example by implementing Runnable interface

class Multi3 implements Runnable{


public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
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 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).
Commonly used methods of Thread class

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.
Thread Priority
Thread Priority: In java each thread is assigned a priority which affects the order in which it is
scheduled for running. Threads of same priority are given equal treatment by the java scheduler.
The thread class defines several priority constants as:
MIN_PRIORITY =1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
► Thread priorities can take value from 1-10
Thread has the following methods
1) setPriority () This method is used to assign new priority to the thread Syntax: Thread.setPriority
(priority value);
2) getPriority() It obtain the priority of the thread and returns integer value. Syntax: int
Thread.getPriority ();
Example: Thread priorities

public class JavaSetPriorityExp1 extends Thread


{
public void run()
{
System.out.println("Priority of thread is: "+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
// creating one thread
JavaSetPriorityExp1 t1=new JavaSetPriorityExp1();
// print the maximum priority of this thread
t1.setPriority(Thread.MAX_PRIORITY);
// call the run() method
t1.start();
}
}
Example: Thread priorities
public class JavaSetPriorityExp4 extends Thread
{ public void run()
{
System.out.println("running...");
}
public static void main(String args[])
{
// creating one thread
JavaSetPriorityExp4 t1=new JavaSetPriorityExp4();
JavaSetPriorityExp4 t2=new JavaSetPriorityExp4();
// set the priority
t1.setPriority(4);
t2.setPriority(7);
// print the user defined priority
System.out.println("Priority of thread t1 is: " + t1.getPriority()); //4
System.out.println("Priority of thread t2 is: " + t2.getPriority()); //7
// this will call the run() method
t1.start();
} }
Synchronization in Java

Generally threads use their own data and methods provided inside their run() methods.
► But if we wish to use data and methods outside the thread’s run() method, they may compete for
the same resources and may lead to serious problems.
► Java enables us to overcome this problem using a technique known as Synchronization.
► For ex.: One thread may try to read a record from a file while another is still writing to the same
file.
► When the method declared as synchronized, Java creates a "monitor" and hands it over to the
thread that calls the method first time.
Syntax:
synchronized (lock-object)
{ .......... // code here is synchronized }
Rules for Synchronization
A thread must acquire the object lock associated with a shared resource, before it can enter the
shared resource.
The runtime system ensures that no other thread can enter a shared resource if another thread
already holds the object lock associated with the shared resource.
If a thread cannot immediately acquire the object lock, it is blocked, that is, it must wait for the lock
to become available.
When a thread exits a shared resource, the runtime system ensures that the object lock is also handed
over. If another thread is waiting for this object lock, it can proceed to acquire the lock in order to
access to the shared resource.
► The keyword ‘synchronized’ and the lock forms the basis for implementing synchronized
execution of code.
There are two different ways in which execution of code can be synchronized:
 synchronized methods  synchronized blocks
Synchronization Example
public class Synchronization implements Runnable {
{ bookticket (name, j);
int tickets = 3; }
static int i = 1, j = 2, k = 3; else
synchronized void bookticket (String name, int wantedtickets) {
{ bookticket (name, k);
if (wantedtickets <= tickets) }
{ }
System.out.println (wantedtickets + " booked to " + name); public static void main (String[]args)
tickets = tickets - wantedtickets; {
} Synchronization s = new Synchronization ();
else Thread t1 = new Thread (s);
{ Thread t2 = new Thread (s);
System.out.println ("No tickets to book"); Thread t3 = new Thread (s);
} t1.setName ("t1");
} t2.setName ("t2");
public void run () t3.setName ("t3");
{ t1.start ();
String name = Thread.currentThread ().getName (); t2.start ();
if (name.equals ("t1")) t3.start ();
{ }
bookticket (name, i); }
Deadlock
 Synchronized keyword is used to make the class or method thread-safe which means only one
thread can have lock of synchronized method and use it, other threads have to wait till the lock
releases and anyone of them acquire that lock.
 It is important to use if our program is running in multi-threaded environment where two or more
threads execute simultaneously. But sometimes it also causes a problem which is called Deadlock.
 Deadlock in java is a part of multithreading.
 Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by
another thread and second thread is waiting for an object lock that is acquire d by first thread.
 Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
Inter –thread communication
When more than one thread uses a shared resource they need to synchronize with each other.
► While using a shared resource the threads need to communicate with each other, to get the
expected behavior of the application.
► Java provides some methods for the threads to communicate
Java provide benefits of avoiding thread pooling using inter-thread communication.
The wait(), notify(), and notifyAll() methods of Object class are used for this purpose.
These method are implemented as final methods in Object, so that all classes have them.
► All the three method can be called only from within a synchronized context
1. wait() : This method is used to make the particular Thread wait until it gets a notification. This
method pauses the current thread to the waiting room dynamically.
2. notify(): wakes up a thread that called wait() on same object.
3. notifyAll() : wakes up all the thread that called wait() on same object
Thank You

You might also like