Unit3_Exception handling & Multithreading
Unit3_Exception handling & Multithreading
Chapter 3
Marks-12
Exception handling & Multithreading
Exception
• Exception is an abnormal condition.
• An Exception is a condition that is caused by a run-time error in the program.
• When java interpreter encounters an error such as dividing an integer by zero, it creates an
exception object and throws it.
• An Exception interrupts the normal flow of the program.
• When an exception occurs program gets terminated abnormally.
• In such cases system generated error messages are displayed.
• Exceptions can be handled.
• Exception can occur at runtime (known as runtime exceptions) as well as at compile-time
(known Compile-time exceptions).
1
333
Java Programming (314317) Chapter-3
1) Checked exceptions
• All exceptions other than Runtime Exceptions are known as checked exceptions.
• Compiler checks them during compilation
• If these exceptions are not handled/ declared in the program, it will give compilation
error.
• Examples of Checked Exceptions :-
– ClassNotFoundException
– IllegalAccessException
– NoSuchFieldException
– EOFException etc.
2) Unchecked exceptions
• Runtime Exceptions are known as unchecked exceptions.
• the compiler do not check whether the exceptions are handled/declared in the program
• But it is the duty of the programmer to handle these exceptions and provide a safe exit.
• Examples of Unchecked Exceptions :-
– ArithmeticException
2
333
Java Programming (314317) Chapter-3
– ArrayIndexOutOfBoundsException
– NullPointerException
– NegativeArraySizeException etc.
1) try block
• The code which might raise exception must be enclosed within try-block
• try-block must be followed by either catch-block or finally-block, at the end.
• ode inside try-block must always be wrapped inside curly braces
• Three forms
1. try-catch block
2. try-finally block
3. try-catch-finally blocks
• Syntax:
try
{
//statements that may cause an exception
}
3
333
Java Programming (314317) Chapter-3
2) catch block
• Contains handling code for any exception raised from corresponding try-block and it must
be enclosed within catch block
• code inside catch-block must always be wrapped inside curly braces
• Syntax:
catch (TypeException object)
{
//error handling code
}
3) finally block
• A finally statement must be associated with a try statement.
• finally block is executed regardless of whether respective exception is handled or not
• used to perform clean-up activities or code clean-up
• Two forms
– try-finally
– try-catch-finally
• Syntax:
finally
{
// block of code to be executed before try block ends
}
4) throw clause
• to throw/raise exception explicitly at runtime
• throw keyword is used to throw user-defined exception or custom exception
• We can throw either checked or unchecked exception.
• Syntax
throw new ThrowableInstance();
• Example:
throw new ArithmeticException("/ by zero");
5) throws clause
• The throws keyword is used to declare an exceptionalong with the method definition.
• Any number of exceptions can be specified using throws clause, but they are all need to be
separated by commas.
• It is mainly used for checked exception
• Used to indicate that this method might throw one of the listed type exceptions.
• The caller of these methods has to handle the exception using a try-catch block.
• Syntax:
void method_name() throws TypeException1, TypeException2,…, TypeExceptionN
{
// body of the method
}
4
333
Java Programming (314317) Chapter-3
try-catch block:
try
{
//statements that may cause an exception
}
catch (TypeException object)
{
//error handling code
}
5
333
Java Programming (314317) Chapter-3
multi-catch block:
try
{
//statements that may cause an exception
}
catch (TypeException1 object)
{
//error handling code
}
catch (TypeException2 object)
{
//error handling code
}
……
try
{
int x = a[2] / 0;
}
catch (ArithmeticException e2)
{
System.out.println("division by zero ");
}
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("Invalid array index");
}
}
}
7
333
Java Programming (314317) Chapter-3
8
333
Java Programming (314317) Chapter-3
}
}
Sr.
throw keyword throws keyword
No.
throw is used to explicitly throw an
1 throws is used to declare an exception.
exception.
checked exception can not be propagated checked exception can be propagated with
2
without throw. 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.
You can declare multiple exception e.g.
5 You cannot throw multiple exception public void method()throws
IOException,SQLException.
import java.util.*;
class NegativeException extends Exception
{
NegativeException(String msg)
{
super(msg);
}
}
9
333
Java Programming (314317) Chapter-3
class NegativeDemo
{
public static void main(String args[])
{
int age=0;
String name;
Scanner sc=new Scanner(System.in));
try
{
if(age<0)
throw new NegativeException("Age is negative");
else
System.out.println("age is positive");
}
catch(NegativeException e)
{
System.out.println(e);
}
}
}
4.2Multithreading
• A multithreaded program contains two or more parts that can run concurrently. Multithreading
is a specialized form of multitasking
• Each part of such a program is called a thread. A thread is a single sequential flow of control
within a program. Each thread defines a separate path of execution.
• Threads are lightweight processes. They share the process’s resource, including memory and
are more efficient.
• JVM allows an application to have multiple threads of execution running concurrently.
• Thread has a priority. Threads with higher priority are executed in preference to threads with
lower priority. Overhead of switching between threads is less.
• Advantages:
1. Reduces the computation time.
2. Improves performance of an application.
3. Threads distribute the same address space so it saves the memory.
4. Context switching between threads is usually less costly than between processes.
10
333
Java Programming (314317) Chapter-3
5. Cost of communication between threads is comparatively low.
Creation of Thread
Two ways
1. Create a class that extends the Thread class
2. Create a class that implements the Runnable interface
The run () method makes up entire body of thread and is the only method in which the threads
behaviour can be implemented.
11
333
Java Programming (314317) Chapter-3
12
333
Java Programming (314317) Chapter-3
class ThreadEx1
{
public static void main(String [] args )
{
MyThread mt = new MyThread();
Thread th = new Thread(mt);
th.start();
}
}
13
333
Java Programming (314317) Chapter-3
1) New Born State
• When a thread object is created it is said to be in a new born state.
• It can be scheduled for running by start() or killed by stop().
• If start( ) method is called then the thread goes to ready to run mode.
• If the stop( ) method is called then the thread goes to dead state.
2) Runnable State:
• It means that thread is ready for execution and is waiting for the availability of the processor
i.e. the threads has joined the queue and is waiting for execution.
• If all threads have equal priority then they are given time slots for execution in round robin
fashion.
• The thread that relinquishes control joins the queue at the end and again waits for its turn. A
thread can relinquish the control to another before its turn comes by yield().
3) Running State:
• It means that the processor has given its time to the thread for execution.
• The thread runs until it relinquishes (give up) control on its own or it is pre-empted by a higher
priority thread.
• The thread can finish its work and end normally.
• The thread can also be forced to give up the control when one of the following conditions arise
1. A thread can be suspended by suspend ( ) method. It is resumed by using the resume ()
method.
2. A thread can be made to sleep for a particular time by using the sleep (milliseconds)
method.
It is wake up after time elapses.
3. A thread can be made to wait until a particular event occur using the wait() method. It is
wake up by notify ( ) method.
4) Blocked state:
• A thread can be temporarily suspended or blocked from entering into the runnable and running
state by using either of the following thread method
1. suspend()
2. wait()
3. sleep()
• Suspended thread is resumed by using the resume() method.
• Sleeping thread wakes up after time elapses/ over
• Waited thread wakes up by notify( ) method.
5) Dead State:
• Whenever we want to stop a thread form running further we can call its stop().
• The running thread ends its life when it has completed executing the run() method which is
called natural dead.
• The thread can also be killed at any stage by using the stop( ) method.
14
333
Java Programming (314317) Chapter-3
Write a program to create two threads, one to print numbers in original order and other
to reverse order from 1 to 50.
ot.start();
rt.start();
}
}
Thread Methods:
1) start()
– Creates a new thread and makes it runnable
– This method can be called only once.
15
333
Java Programming (314317) Chapter-3
– Syntax:
public void start()
{
}
– Ex: threadobj.start()
2) run()
– Task to be executed by thread is defined in run() method.
– Syntax:
public void run()
{
//thread task here
}
3) stop()
– Whenever we want to stop a thread from running further, call stop() method.
– Syntax:
public void stop()
{
}
– Ex: threadobj.stop()
– This method causes the thread to move to dead state.
– The stop may used when the premature death of thread is desired.
4) suspend()
– This method puts a thread in suspended state and can be resumed using resume() method.
– Syntax :
public void suspend()
{
}
5) resume()
– This method resumes a thread which was suspended using suspend() method.
– Syntax :
public void resume()
{
}
6) yield()
– The yield() method causes the currently executing thread object to temporarily pause and
allow other threads to execute
– Syntax :
public static void yield()
{
}
16
333
Java Programming (314317) Chapter-3
7) wait()
– This method causes the current thread to wait until another thread invokes the notify()
method or the notifyAll() method for this object.
– syntax :
public final void wait()
{
}
8) sleep()
• Syntax:
public void sleep(int m) throws InterruptedException
public void sleep(int m, int n) throws InterruptedException
– The thread sleeps for m milliseconds, plus n nanoseconds.
Thread Exceptions
• Mostly call to sleep() method is enclosed within a try block and followed by catch block. This
is because the sleep() method threads an exception, which must be caught. If exception thread
is not catched, program, will not compile.
• Java run system will throw IllegelThreadStateException whenever attempt is made to invoke a
method that a thread cannot handle in given state.
• For example, a sleeping thread cannot deal with the resume() method because a sleeping thread
cannot receive any instructions.
• When thread method is called which is throwing an exception the appropriate exception
handler must be supplied which catch exception thrown by thread.
• The catch statement can take any one of the following four forms
1. catch(ThreadDeath e)
{
- ------- //Killed thread
}
2. catch(InterruptedException e)
{
- ------- //cannot handle it in current state
}
3. catch(IllegalArgumentException e)
{
- --------- //Illegal method argument
}
4. catch(Exception e)
{
- -------- // any other
}
17
333
Java Programming (314317) Chapter-3
➢ Thread PriorityMethods:
1. setPriority:
– This method is used to assign new priority to the thread.
– Syntax:
public void setPriority(int number)
– Example:
threadobj.setPriority(Thread.MIN_PRIORITY);
2. getPriority:
– It obtain the priority of the thread and returns integer value.
– Syntax:
public intgetPriority();
– Example:
int prority=threadobj.getPriority();
ot.setPriority(Thread.MIN_PRIORITY);
tt.setPriority(Thread.MAX_PRIORITY);
ot.start();
tt.start();
}
}
19
333
Java Programming (314317) Chapter-3
3. notifyAll()-
It wakes up all the threads that called wait() on the same object.
public final void notifyAll()
Synchronization
• When two or more threads wants to access to a shared resources, there is requirement of the
shared resource must be used by only one thread at a time.
• The synchronized keyword is used to achieve this.
• Synchronized code will only be executed by one thread at a time.
• When we declare a method synchronized, Java creates a “monitor or lock” and hands it to the
thread that calls the method first time.
• As long as the method holds the monitor, no other thread can enter the synchronized section of
code.
• Two ways:
1. Synchronized mehod
synchronized returntype methodname(paralist)
{
2. Synchronized block
synchronized(sync_object)
{
class Shared
{
synchronized void display(String msg)
{
System.out.print("["+msg);
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
20
333
Java Programming (314317) Chapter-3
}
System.out.println("]");
}
}
class MyThread extends Thread
{
Shared sh;
String msg;
MyThread(String ms,Shared s)
{
msg=ms;
sh=s;
}
public void run()
{
sh.display(msg);
}
}
class SyncMethod
{
public static void main(String args[])
{
Shared sh=new Shared();
MyThread th1=new MyThread("Hi",sh);
MyThread th2=new MyThread("Hello",sh);
MyThread th3=new MyThread("Thanks",sh);
th1.start();
th2.start();
th3.start();
}
}
class Shared
{
void display(String msg)
{
System.out.print("["+msg);
try
{
Thread.sleep(500);
}
21
333
Java Programming (314317) Chapter-3
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("]");
}
}
class MyThread extends Thread
{
Shared sh;
String msg;
MyThread(String ms,Shared s)
{
msg=ms;
sh=s;
}
public void run()
{
synchronized(sh)
{
sh.display(msg);
}
}
}
class SyncBlock
{
public static void main(String args[])
{
Shared sh=new Shared();
MyThread th1=new MyThread("Hi",sh);
MyThread th2=new MyThread("Hello",sh);
MyThread th3=new MyThread("Thanks",sh);
th1.start();
th2.start();
th3.start();
}
}
Deadlock
• Deadlock in java is a part of multithreading
• 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 acquired by first thread.
22
333
Java Programming (314317) Chapter-3
• Since, both threads are waiting for each other to release the lock, the condition is called
deadlock.
Fig3: Deadlock
• Thread1 locks/holds ResourceA and it is waiting for ResourceB which is locked/held by
Thread2. Similarly, Thread2 locks/holds ResourceB and it is waiting for ResourceA which
is locked/held by Thread1. That is both the threads are waiting for each other to release the
resources. But no one is releasing. Hence, system functioning is stopped & this situation is
known as Deadlock.
• For Example:
Thread A
synchronized resource1
{
synchronized resource2
{
}
}
Thread B
synchronized resource2
{
synchronized resource1
{
}
}
23
333
Java Programming (314317) Chapter-3
Questions on Chapter 4:
1) Explain the following clause w.r.t. exception handling : (i) try (ii) catch (iii) throw (iv) finally
2) Describe types of Errors and Exceptions in details.
3) What is an exception ? How it is handled ? Give suitable example.
4) Write a program to accept password from user and throw “Authentication failure” exception if
password is incorrect.
5) Write program. Define an exception called ‘No match Exception’ that is thrown when a string
is not equal to MSBTE”.
6) What is thread priority ? Write default priority values and methods to
7) change them.
8) What is synchronization ? When do we use it ? Explain synchronization of two threads
9) Describe following methods of thread :
(i)suspend ( ) (ii) resume ( ) (iii) sleep ( ) (iv) notify ( ) (v) stop () (vi) wait ( )
10) Write a thread program for implementing the ‘Runnable interface’.
11) Explain life cycle of thread with a neat diagram.
12) What is thread ? Draw thread life cycle diagram in Java.
13) Write a program to create two threads, one to print numbers in even no and odd no from 1 to
50.
14) Write a program to create two threads so one thread will print 1 to 10 numbers whereas other
will print 11 to 20 numbers.
15) Write a program to define two threads for displaying even and odd numbers respectively with a
delay of 500 ms after each number.
24