Unit No - 4
Unit No - 4
Unit No.4
Exception Handling and Multithreading
Error – These are not exceptions but the problems that arise beyond the control of the user
or the programmer.
Types of Errors –
Compile Time Error – All the syntax errors given by Java Compiler are known as
Compile Time Errors.
Missing semicolon
Missing brackets in class or method
Missing double quotes in String etc.
Run Time Error – Sometimes, a program may compile successfully, but may not run
properly because of wrong logic. The errors which are generated while program is
running are known as Run Time Errors.
Opening a file which does not exists
Trying to store value at negative index value
Accessing element that are out of capacity of array etc.
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions.
When an error occurs within a method, the Interpreter creates an object and hands it. The object,
called an exception object, contains information about the error, including its type and the state
of the program when the error occurred. Creating an exception object and handing it to the
runtime system is called throwing an exception.
If the exception object is not handled properly then the interpreter will display an error message.
Categories of Exceptions –
Unchecked Exceptions – Unchecked Exceptions are the exceptions which are not
checked by the compiler at the run time of compiling program.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class.
The exception class is a subclass of the Throwable class.
Other than the exception class there is another subclass called Error which is derived
from the Throwable class.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Exception Handling –
The purpose of exceptional handling is to detect & report an exception so that the proper
action can be taken & prevent the program which is automatically terminate or stop the
execution due to exception.
1. try – The program statements that to be monitored for exceptions are contained within
the try block. If an exception occurs within try block then it is thrown.
2. catch – code can catch the exception & handle it in some relational manner
3. throw – System generated exceptions are automatically thrown by java run time system.
To manually throw an exception ‘throw’ keyword is used.
4. throws – any exception that is generated out of a method must be specified as ‘throws’
clause.
5. finally –any code that must be executed before a method returns is put in a finally block.
Try Block
Exception object
Statements that cause an
Throws exception creator
exception
object
try
//statements
____
finally
//statements }}
Program –
class exc
int a=10;
int b=0;
int c;
try
c=a/b;
Output -
C:\my>java exc
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on an unlocked
IllegalMonitorStateException
thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread
state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
Exception Description
ClassNotFoundException Class not found.
Attempt to clone an object that does not implement the
CloneNotSupportedException
Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
try block can be followed by multiple catch blocks. The syntax for multiple catch blocks are as
following:
try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
- If an exception occurs in the protected code, the exception is thrown to the first catch
block in the list.
- If the data type of the exception thrown matches ExceptionType1, it gets caught there.
- If not, the exception passes down to the second catch statement. This continues until the
exception either is caught or falls through all catches, in which case the current method
stops execution and the exception is thrown down to the previous method on the call
stack.
Program –
class mexc
try
int a=0;
int b=10/a;
int c[]={1,2,3};
Output –
C:\my>java mexc
Program 2-
class mcatch
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x = a[2]/b - a[1]; // Array Error because no element at 2nd Position
}
catch(ArithmeticException e)
{
System.out.println("Divide by Zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong Data Type");
}
int y = a[1]/a[0];
System.out.println("y= "+y);
}
}
Output –
C:\my>java mcatch
Divide by Zero
y= 2
Syntax –
try
{
//statements
try
{
//statements
}
catch (Exception eobj)
{
//statements to handle exception
}
}
catch (Exception-Type1 eobj)
{
//statements to handle exception
}
Program 1 –
class nTry
{
public static void main(String args[])
{
int num1=100;
int num2=50;
int num3=50;
int r;
try
{
r = num1 / (num2-num3);
System.out.println("Result =" +r);
try{
r = num1 / (num2-num3);
Sou.Venutai Chavan Polytechnic,Pune. 9
Java Programming (22412)
Output –
C:\my>java nTry
New Arithmetic Error
Program 2-
class mtry
{
public static void main(String args[])
{
try
{
try
{
System.out.println("going to divide");
int b= 9/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("other statement...");
}
catch (Exception e)
{
System.out.println("Handled");
}
}
}
Output –
C:\my>java mtry
going to divide
java.lang.ArithmeticException: / by zero
other statement...
Program -
class ThrowE
if (age<18)
else
validate(13);
System.out.println("rest of code");
Output –
C:\my>java ThrowE
at ThrowE.validate(ThrowE.java:6)
at ThrowE.main(ThrowE.java:13)
Syntax –
//code
Program –
import java.io.IOException;
class simple
{
void m() throws IOException
{
throw new IOException("New Error");
}
void p()
{
try
{
m();
}
catch (Exception e)
{
System.out.println(e);
}
}
Output –
C:\my>java simple
java.io.IOException: New Error
Normal flow
throw throws
It is used to explicitly throw an exception It is used to declare an exception
Checked exceptions cannot be propagated Checked exceptions can be propagated without
without throw throw
It is followed by an instance It is followed by a class
Syntax –
Class class_name extends Exception
{
//Methods & implementation
}
Program –
class MyException extends Exception
{
public String show()
{
class TestMy
{
public static void main(String args[])
{
int a=10;
try
{
if(a==10)
{
throw new MyException();
}
else
{
System.out.println("other code");
}
}
catch(MyException e)
{
System.out.println("Exception =" + e.show());
}
}
}
Output –
C:\my>java TestMy
Exception =My Error
Multithreading
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation etc.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Newborn State –
Thread can move to running mode by invoking the start() method and it can be killed by
using stop() method.
Runnable State –
In this state Thread is ready for execution & it is waiting for the availability of the
processor.
By yield() method, it is possible to move control to another thread.
Running State –
It means thread is in its execution mode because the control of CPU is given to that
particular thread (i.e. Processor has given its time to that thread).
It can be move in three different situation from running mode.
o Suspended() – a suspended thread can be revived by using resume() method.
o Sleep(t) – a thread can be sleep for specific time period using sleep() method,
where time is in milliseconds. The thread re-enters into runnable state as soon as
this time period is elapsed.
o Wait() – a thread is waiting until some event occurs. A thread can be scheduled to
run again using the notify() method.
Blocked State –
A thread is called in Blocked State when it is not allowed to entering in Runnable State or
Running State.
It happens when thread is in waiting mode, suspended or in sleeping mode.
A blocked thread is considered as “not runnable” but not dead.
Dead Thread –
When a thread is completed executing its run() method the life cycle of that particular
thread is end.
We can kill thread by invoking stop() method for that particular thread and send it to be
in Dead State.
Thread Creation
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r,String name)
The easiest way to create a thread is to create a class that implements the runnable interface.
After implementing runnable interface , the class needs to implement the run() method, which is
of form,
run() method introduces a concurrent thread into your program. This thread will end
when run() method terminates.
You must specify the code that your thread will execute inside run() method.
run() method can call other methods, can use other classes and declare variables just like
any other normal method.
class MyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
Output –
To call the run() method, start() method is used. On calling start(), a new stack is provided to
the thread and run() method is called to introduce the new thread into the program.
This is another way to create a thread by a new class that extends Thread class and create an
instance of that class. The extending class must override run() method which is the entry point of
new thread.
classMyThreadDemo
{
public static void main( String args[] )
{
MyThread mt = new MyThread();
mt.start();
}
}
Output :
Here, we must override the run() and then use the start() method to run the thread. Also, when
you create MyThread class object, Thread class constructor will also be invoked, as it is the
super class, hence MyThread class object acts as Thread class object.
Thread Methods
Thread Priority
Each java thread has its own priority which decides the order of thread to be schedule.
The threads of equal priority will be given same treatment by java scheduler and they will
follow the FCFS (First Come First Serve) algorithm.
User can also set the priority of thread by using the setPriority() method as follow:
ThreadName.setPriority(int Number);
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Program –
System.out.println("First Thread");
System.out.println("Second Thread");
FT t1 = new FT();
ST t2 = new ST();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
Output –
Second Thread
Second j = 1
Second j = 2
Second j = 3
Second j = 4
Second j = 5
First Thread
First i = 1
First i = 2
First i = 3
First i = 4
First i = 5
Synchronization
What is a Monitor?
A monitor is a set of multiple routines which are protected by a mutual exclusion lock. None of
the routines in the monitor can be executed by a thread until that thread acquires the lock. This
means that only ONE thread can execute within the monitor at a time. Any other threads must
wait for the thread that’s currently executing to give up control of the lock.
However, a thread can actually suspend itself inside a monitor and then wait for an event to
occur. If this happens, then another thread is given the opportunity to enter the monitor. The
thread that was suspended will eventually be notified that the event it was waiting for has now
occurred, which means it can wake up and reacquire the lock.
What is a Semaphore?
A semaphore is a simpler construct than a monitor because it’s just a lock that protects a
shared resource – and not a set of routines like a monitor. The application must acquire the lock
before using that shared resource protected by a semaphore.
A mutex is the most basic type of semaphore, and mutex is short for mutual exclusion.
In a mutex, only one thread can use the shared resource at a time. If another thread wants to
use the shared resource, it must wait for the owning thread to release the lock.
Lock –
Types of Syncronization –
Process Synchronization
Thread Synchronization
Thread Synchronization
Mutual Exclusion –
Synchronized block
Synchronized method
Inter-Thread Communication
Program -
Without Syncronization –
class table
{
void print(int n)
{
for (int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class use
{
public static void main(String args[])
{
table obj = new table();
FT f = new FT(obj);
ST s = new ST(obj);
t1.start();
t2.start();
}
}
Output -
C:\my>java use
5
100
10
200
15
300
20
400
25
500
Program –
class table
{
class use
{
public static void main(String args[])
{
table obj = new table();
FT t1 = new FT(obj);
ST t2 = new ST(obj);
t1.start();
t2.start();
}
}
Output –
C:\my>java use
5
10
15
20
25
100
200
300
400
500
class message
{
synchronized void dispHi()
{
System.out.println("Hi");
}
}
}
class TComm
{
public static void main(String args[])
{
message obj = new message();
FT t1=new FT(obj);
ST t2=new ST(obj);
t.start();
tt.start();
}
}
Output –
Hi
Hi
Hello
Hi
Hello
Hello …
class message
{
boolean r=false;
{
m=m1;
}
public void run()
{
while(true)
m.dispHi();
}
}
class TComm
{
public static void main(String args[])
{
message obj = new message();
FT t1=new FT(obj);
ST t2=new ST(obj);
t.start();
tt.start();
}
}
Output –
Hi
Hello
Hi
Hello
Hi
Hello
wait() - 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.
notify() - 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.
notifyAll() - Wakes up all threads that are waiting on this object's monitor.
class Customer
int balance=10000;
System.out.println("going to withdraw...");
if(balance<amount)
try{
wait();
}catch(Exception e){}
balance-=amount;
System.out.println("withdraw completed...");
System.out.println("going to deposit...");
balance+=amount;
notify();
Customer o;
ft(Customer obj)
{ o=obj; }
Customer o;
st(Customer obj)
{ o=obj; }
class Test{
ft t1 = new ft(c);
st t2 = new st(c);
t1.start();
t2.start();
Thread Programs
Main Thread Program – currentThread(), setName(), setPriority()
class MainThread
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current Thread =" +t);
t.setName("MAINTHREAD");
System.out.println("Current Thread =" +t);
t.setPriority(3);
System.out.println("Current Thread =" +t);
}
}
Output –
Current Thread =Thread[main,5,main]
Current Thread =Thread[MAINTHREAD,5,main]
Current Thread =Thread[MAINTHREAD,3,main]
Creating multiple threads by extending Thread Class (Multiple threads performing same
task)
class FT extends Thread
{
public void run()
{
System.out.println("Hello");
}
}
public class ThreadDemo
{
public static void main(String args[])
{
FT t1=new FT();
t1.setName("First");
t1.start();
FT t2=new FT();
t2.setName("Second");
t2.start();
FT t3=new FT();
t3.setName("Third");
t3.start();
Hello
}
}
Output –
Hello
t2 t3
t1
Hello
Hello
{
FT()
{
setName("FirstThread");
start();
}
public void run()
{
System.out.println("Hello");
System.out.println(getName());
}
}
public class ThreadDemo
{
public static void main(String args[])
{
FT t1=new FT();
}
}
Output –
Hello
FirstThread
setName("FirstThread");
start();
}
public void run()
{
System.out.println("Hello");
System.out.println(getName());
}
}
Output –
Hello
FirstThread
Bye
SecondThread
Creation of Thread, One thread should print Even numbers & another thread should print
Odd numbers.
class FT extends Thread
{
ST t2=new ST();
t2.setName("Odd");
System.out.println(t2.getName());
t2.start();
Output –
Even
Odd
0
2
4
6
8
1
3
5
7
9
System.out.println("Exit...");
}
}
Output –
Thread
1
2
3
4
5
Exit...
Create 2 Threads, one should print “Hello” and second should print “Bye” with
implementing Runnable Interface
class FT implements Runnable
{
public void run()
{
System.out.println("First Thread");
System.out.println("Hello");
System.out.println("Exit...");
}
}
class ST implements Runnable
{
public void run()
{
System.out.println("Second Thread");
System.out.println("Bye");
System.out.println("Exit...");
}
}
public class Thread_Interface
{
public static void main(String[] args)
{
FT objF = new FT(); //class object
Thread t1 = new Thread(objF);
t1.start();
Output –
First Thread
Hello
Exit...
Second Thread
Bye
Exit...