Chapter - 5 Exception Handling Multithreaded Programming
Chapter - 5 Exception Handling Multithreaded Programming
Chapter - 5 Exception Handling Multithreaded Programming
An exception is an abnormal condition that arises in a program at run time. In other words, an exception is a
run-time error
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 exception is occurred , an object which represents that exception is created and passed to the method
where the exception has occurred.this object contains detail information about the exception ,which can be
retrived and processed.
All exception types are subclasses of a class Throwable.Thus, Throwable is at the top of the exception class
hierarchy.
Throwable
Exception Error
RuntimeException
1
JAVA PROGRAMMING
Types of Exception:
There are mainly three types of exceptions
1.Checked Exception.
2.Unchecked Exception.
3.Error.
1.Checked Exception.
A checked exception is an exception that occurs at the compile time, these are also called as compile time
exceptions. .The exception that can be preditated by the programmer falls under this category.
For example, File that needs to be opened is not found.
Exception(class) Meaning
ClassNotFoundException A class can not found.
IllegalAccessException An illegal access to a class was attempted
InterruptedException A thread has been interrupted.
NoSuchFieldException A requested field does not exist
NoSuchMethodException A requested method does not exist
2.Unchecked Exception.
An Unchecked exception is an exception that occurs at the time of execution, these are also called as Runtime
Exceptions, these include programming bugs, such as logic errors or improper use of an API. runtime
exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the
array .
Exception(class) Meaning
ArithmeticException 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
2
JAVA PROGRAMMING
3.Unrecoverable error.
These are not exceptions at all, but problems that arise beyond the control of the user or the programmer.
Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a
stack overflow occurs, an error will arise. This type of error is not possible to handle in code.
2.Explain what happens when we don’t handle the exceptions? OR Explain uncaught exceptions.
When the Java run-time system detects the exception like divide by zero, it constructs a new exception object
and then throws this exception.
This exception must be caught by an exception handler. If we don‟t define handler in our program then the
exception is caught by the default handler provided by the Java run-time system.
The default handler displays a string describing the exception, prints a stack trace from the point at which the
exception occurred, and terminates the program.
If we define exception handler in our program then exception is handle by our program and appropriate
message is displayed on the screen.
Ex:
class uncaught
{
public static void main(String args[])
{
int a=0;
int b=7/a;
}
}
Output:Exception in thread "main" java.lang.ArithmeticException: / by zero at uncaught.main(a.java:6)
3
JAVA PROGRAMMING
As we don‟t any mechanism for handling exception in the above program,so this will lead to an exception at
runtime and the java run-time system will construct an exception and then throw it.
Then the default handler will handle the exception and will print the details of the exception.
Exception handling is the mechanism to handle runtime problems. We need to handle such problems to prevent
abnormal termination of program. So Exception handling mechanism minimizes the chances of a system crash
Exception handling mechanism provides more specific information about program errors to user.
Exception Handling is done by transferring the execution of a program to an appropriate exception handler
when exception occurs.
Exception handler is a block of code to handle thrown exception. If program recover exception then program
can resume executing after the exception handler has executed.
Exception handlingis done using five keywords, try ,catch, throw, throws, finally.
try block contains program statements those may generate errors. It means write the code that you want to
monitor inside a try block.
After try block,include a catch block that specify exception type that you wish to catch.It means catch block
defines a block of statements to handle the generated exception inside the try block.
If an exception occurs in try block ,the catch block that follows the try is checked,if the type of exception that
occurred match with the catch block then the exception is handed over to the catch block which then handles
it.
Example:
class Exc2
{
public static void main(String args[])
4
JAVA PROGRAMMING
{
int b=0, a=5;
try
{
System.out.println("sum=”+(a+b));
System.out.println("sub=”+(a-b));
System.out.println("div=”+(a/b));
}
catch (ArithmeticException e)
{
System.out.println("system message"+e.getMessage());
System.out.println("user message : divided by zero”);
}
}
}
Output:
system message/ by zero
user message : divided by zero
In some cases ,more than one Exception may be generated in try{} block .To handle this type of situation ,you
can specify two or more catch{} block.
Each catch{} block contain different type of exception.If an exception occurs in the try{} block,the exception
is passed to the first catch{} block in the list.
If the exception type matches with the first catch{ }block it excuted otherwise it is passed down to the next
catch{} block.
After one catch{} stat. executes ,the others are bypassed.
structure
try
{
// block of code to monitor for errors.
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
5
JAVA PROGRAMMING
}
catch (ExceptionType2 exOb1)
{
// exception handler for ExceptionType2
}
Example:
class Exc2
{
public static void main(String args[])
{
try
{
int a=args.length;
System.out.println("a=”+a);
int b=6/a;
int arr[]={1,2,3};
arr[5]=8;
}
catch (ArithmeticException e)
{
System.out.println("user message : divided by zero”);
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("array index out of bound”);
}
}
}
Output: e:>java Exc2
a=0
user message : divided by zero
e:>java Exc2 hello
a=1
array index out of bound
6
JAVA PROGRAMMING
When you use multiple catch{} statements,it is important that exception subclasses must come before any of
their superclasses.
This is because a catch{} statement that uses a superclass will catch exceptions of that type plus any of its
subclasses.
Thus a subclass would never be reached if it came after its superclass.
Example:
class Exc2
{
public static void main(String args[])
{
try
{
int arr[]={1,2,3};
arr[4]=10/0;
}
catch (Exception e) //this block handles all Exception.
{
System.out.println("user message : divided by zero”);
}
catch (ArrayIndexOutOfBoundsException e1) //this block is unreachable.
{
System.out.println("array index out of bound”);
}
}
}
Output: compilation error
The try{} block can be nested.That is try{} block can be inside the block of another try{}.
Nested try{} block is used when a part of a block may cause one error while entire block may cause another
error.
In case if inner try{} block does not have a catch handler for a particular exception then the outer try{} block
catch handlers are inspected for a match.
Example:
class Exc2
{
public static void main(String args[])
{
7
JAVA PROGRAMMING
try
{
int arr[]={0,2,3};
try
{
int a= 2/0;
}
catch (ArithmeticException e)
{
System.out.println("user message : divided by zero”);
}
arr[4]=5;
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("array index out of bound”);
}
}
}
Output: user message : divided by zero
array index out of bound
7. Explain throw() .
when an exception condition occurs the system automatically throw an exception to inform user that there is
something wrong. However we can also throw exception explicitly based on our own defined condition.
In Java throw keyword is used to explicitly throw an exception.The flow of execution stops immediately after
the throw statement.
syntax throw Throwableinstance;
Throwableinstance must be an object of type Throwable or a subclass of Throwable.only object of Throwable
class or its subclasses can be thrown.
Example1:
class Exc2
8
JAVA PROGRAMMING
{
public static void main(String args[])
{
Throwable t1=new Throwable(“error”);
try
{
System.out.println("exception is thrown”);
throw t1;
}
catch (Throwable e)
{
System.out.println("exception here : “+e);
}
}
}
Output: exception is thrown
exception here : error
Example2:
class Exc2
{
void validate(int age)
{
try
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
catch (ArithmeticException e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
Exc2 e1=new Exc2();
e1.validate(13);
9
JAVA PROGRAMMING
}
}
Output: java.lang.ArithmeticException: not valid
8. Explain throws() .
Example:
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
public static void main(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}
10
JAVA PROGRAMMING
9. Explain finally() .
Sometimes we have situations when a certain piece of code must be executed, no matters if try block is
executed successfully or not, this is done by a „finally‟ block .
It means “finally” is a keyword that executes a block of statements regardless of whether any exception is
generated or not.
A „finally‟ block is written followed by a try block or a catch block, code written inside a finally block is
always executed.
Using a finally block you can execute any cleanup type statements ,return resources to the system ,and execute
other statements like closing file,closing the connection established with database etc..
Example:
class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
11
JAVA PROGRAMMING
Process:
Process is part of computer program that is executed sequentially.
Thread:
Thread is lightweight subprocess , a smallest unit of processing.It is a seprate path of execution.
Threads are independent ,if exception occurs in one thread ,it doesn‟t affect other threads.It share common
memory area.
Threading is a facility to allow multiple activities to coexist within a single process. Every Java program has at
least one thread -- the main thread. When a Java program starts, the JVM creates the main thread and calls the
program's main() method within that thread.
The JVM also creates other threads that are mostly invisible to you for example, threads associated with
garbage collection, object finalization.
Process2
Thread1
Thread2
Thread3
Process3
OS
Thread is executed inside the process.There is context switching between the threads.
There can be multiple processes inside the OS and one process can have multiple threads.
Process Thread
Processes are heavy weight tasks. Threads are light weight tasks.
Processes requires their own separate address space. Threads share same address spaces.
12
JAVA PROGRAMMING
Context switching from one process to other is costly. Context switching from one thread to other is cheap
compared to process.
Interprocess communication is costly and limited Interthread communication is cheap.
Multitasking processes requires more overhead. Multitasking threads requires more overhead.
Java is a multi threaded programming language which means we can develop multi threaded program using
Java.Multithreading in java is a process of executing multiple threads simultaneously.
It means Multithreaded program contains two or more parts that can run simultaneously.For ex. One thread is
writing content on a file at the same time another thread is performing spelling check.
So single program can perform two or more tasks simultaneously.
Multithreading enables you to write very efficient programs that make maximum use of the CPU.
There are some states while executing a thread . We define main five states in thread life cycle in java .
new, runnable, running,blocked, terminated.
The life cycle of the thread in java is controlled by JVM.
blocked
yield() dispatch
terminated thread
completed running sleep
New
The thread is in new state if you create an instance of Thread class but before the call of start() method.
Runnable
The thread is in runnable state after call of start() method, but the thread scheduler has not selected it to be the
running thread.
Running
The thread is in running state if the thread scheduler has selected it.
Blocked
13
JAVA PROGRAMMING
This is the state when the thread is still alive, but is currently not run.
Terminated
A thread is in terminated or dead state when its run() method exits.
Java‟s multithreading system is built upon a Thread class, its methods.and its interface Runnable.
Some methods of Thread class are as below.
extends implements
Thread
15
JAVA PROGRAMMING
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
display t1=new display();
Thread t2=new Thread(t1);
t2.start();
}
}
output: thread is running
The sleep() method of Thread class is used to sleep a thread for specified amount of time.
Syntax: sleep( milliseconds)
it throw InterruptedException type exception.
16
JAVA PROGRAMMING
m2.start();
}
}
output: 1
1
2
2
3
3
4
4
Each thread have a priority. Priorities are represented by a number between 1 and 10.
In most cases, thread schedular schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.
Methods:
setPriority : It is used to set the priority of thread.
getPriority : It is used to get the priority of thread.
}
public static void main(String args[])
{
Test m1=new Test();
17
JAVA PROGRAMMING
In java while working with multiple threads,it may be possible that more than one thread share the same data at
a time.For ex. one thread read data when other thread tries to change it.This might generate error in result.
In this case ,it is necessary to allow one thread to finish its task completely and then allow next thread to
execute.So thread Synchronization to allows a programmer to control threads that are sharing data.
When two or more threads need access to share data,thread synchronization ensure that ,the data will be used
by only one thread at a time.To avoid this problem ,java uses monitor also known as “semaphore” to prevent
data from being loss by multiple threads.
synchronization is mechanism which allows two or more threads to share all the available resources in a
sequential manner.
java use synchronized keyword to ensure that only one thread is in a critical region.critical region is area
where only one thread is run at a time.once thread is in its critical region ,no other thread can enter to that
critical region.In this case ,another thread will has to wait until the current thread leaves its critical region.
Synchronized methods:
18
JAVA PROGRAMMING
class Table
{
synchronized void printTable(int n) //synchronized method
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
19
JAVA PROGRAMMING
t.printTable(100);
}
}
class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
output: with synchronized method without synchronized method
5 5
10 100
15 10
20 200
25 15
100 300
200 400
300 20
400 25
500 500
Synchronized block:
Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method,but you want to synchronize only 5 lines, you can use
synchronized block.
class Table
{
void printTable(int n) //synchronized method
{
synchronized(this)
20
JAVA PROGRAMMING
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
21
JAVA PROGRAMMING
class TestSynchronization2
{
public static void main(String args[])
{
Table obj = new Table(); //only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
output: with synchronized method without synchronized method
5 5
10 100
15 10
20 200
25 15
100 300
200 400
300 20
400 25
500 500
All uncaught exception are handled by code outside of the run() method before the thread terminates.
It is possible for a program to write a new default exception handler.
The default exception handler is the uncaughtException() method of the Thread class.it is called when
exception is thrown from the run() method.
Thread class has two methods for uncaught exception.
1. setDefaultUncaughtExceptionHandler():
This method of Thread class can be used to provide a common exception handler for all the threads.
2. setUncaughtExceptionHandler():
This non static method of thread class which is used to provide handler to a given thread.
22
JAVA PROGRAMMING
import java.lang.*;
class ThreadDemo
{
public static void main(String[] args)
{
Thread t = new Thread(new adminThread());
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("error in " + t.getName() +e.getMessage());
}
});
t.start();
}
}
class adminThread implements Runnable
{
public void run()
{
throw new RuntimeException();
}
}
output: error in thread -0 null
GTU QUESTION:
23
JAVA PROGRAMMING
24