Unit III
Unit III
Unit III
Exception Handling
Basics
Exception:
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
Exception Handling:
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.
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. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed.
That is why we use exception handling in Java.
Types of Java Exceptions
1. Checked exceptions
Examples:
2. Unchecked exceptions
For example :
o ArrayIndexOutOfBounds,
o NullPointerException,
o RunTimeException.
Keywords used in exception handling
try- The try block contains the code that might throw an exception.
Catch- A catch block must be declared after try block. It contains the error handling
code. Note that for each corresponding try block there exists the catch block.
finally- It specifies the code that must be executed even though exception may or may
not Occur.
throw- For explicitly throwing the exception, the keyword throw is used.
throws-The "throws" keyword is used to declare exceptions. It is always used with
method signature.
try-catch block:
The statements that are likely to cause an exception are enclosed within a try block.
There is another block defined by the keyword catch which is responsible for
handling the exception thrown by the try block.
As soon as exception occurs it is handled by the catch block.
The catch block is added immediately after the try block.
Syntax:
try
{
//exception gets generated here
}
catch(Type_of_Exception e)
//exception is handled here
}
Example code for try-catch block
Java Program for try-catch block Output
public class TryCatchExample2 { java.lang.ArithmeticException: / by zero
rest of the code
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");
}
try{
int a[]=new int[5];
System.out.println(a[10]);
}
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");
}
}
Using throw
For explicitly throwing the exception, the keyword throw is used.
The keyword throw is normally used within a method.
We cannot throw multiple exceptions using throw.
Example for throw Output
class Test{ D:\one>javac Test.java
public static void main(String[] args)
{ D:\one>java Test
throw new ArithmeticException("/ by zero"); Exception in thread "main"
} java.lang.ArithmeticException: / by zero
} at Test.main(Test.java:4)
Using throws
There are given some scenarios where unchecked exceptions may occur. They are as follows:
int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3.
3) A scenario where NumberFormatException occurs
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may
be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following
statements.
• Here the Throwable's subclass is actually a subclass derived from the Exception class.
For example -
Throwable's subclass
• Let us see a simple Java program which illustrates this concept.
Java Program[MyExceptDemo.java]
import java.lang.Exception;
MyOwnException(String msg)
super(msg);
class MyExceptDemo
int age;
age=15;
try
if(age<21)
}
catch (MyOwnException e)
System.out.println (e.getMessage());
finally
Output
Multithreaded Programming
Introduction to Thread
Definition: Thread
A thread is a lightweight sub-process that defines a separate path of execution. It is the
smallest unit of processing that can run concurrently with the other parts (other
threads)
of the same process.
Threads are independent.
If there occurs exception in one thread, it doesn't affect other threads.
It uses a shared memory area.
As shown in the above figure, a 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.
DIFFERENCE BETWEEN THREAD AND PROCESS:
PROCESS THREAD
Process is a heavy weight program Thread is a light weight process
Each process has a complete set of its Threads share the same data
own variables
Processes must use IPC (Inter Process Threads can directly communicate with
Communication) to communicate with each other with the help of shared
sibling processes variables
Cost of communication between Cost of communication between threads
processes is high. is low.
Process switching uses interface in Thread switching does not require
operating system. calling an operating system.
Processes are independent of one Threads are dependent of one another
another
Each process has its own memory and All threads of a particular process shares
resources the common memory and resources
Creating & destroying processes takes Takes less overhead to create and
more overhead destroy individual threads
Multithreading
Multithreading in Java is a process of executing multiple threads simultaneously.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
Multitasking
1. New State
A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread by calling start () method, which places the thread in the
runnable state.
A new thread is also referred to as a born thread.
When the thread is in this state, only start () and stop () methods can be called.
Calling any other methods causes an IllegalThreadStateException.
Sample Code: Thread myThread=new Thread();
2. Runnable State:
After a newly born thread is started, the thread becomes runnable or running by
calling the run () method.
A thread in this state is considered to be executing its task.
Sample code: myThread.start();
The start() method creates the system resources necessary to run the thread
3. Running Thread:
Thread scheduler selects thread to go from runnable to running state. In running state
Thread starts executing by entering run () method.
Thread scheduler selects thread from the runnable pool on basis of priority, if priority
of two threads is same, threads are scheduled in unpredictable manner. Thread
scheduler behaviour is completely unpredictable.
4. Waiting/Timed Waiting/Blocked State:
Waiting State:
Sometimes one thread has to undergo in waiting state because another thread starts
executing. A runnable thread can be moved to a waiting state by calling the wait ()
method.
A thread transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.
A call to notify () and notifyAll () may bring the thread from waiting state to runnable
state.
Timed Waiting:
A runnable thread can enter the timed waiting state for a specified interval of time by
calling the sleep () method.
After the interval gets over, the thread in waiting state enters into the runnable state.
Sample Code:
try {
Thread.sleep(3*60*1000);// thread sleeps for 3 minutes
}
catch(InterruptedException ex) { }
Blocked State:
When a particular thread issues an I/O request, then operating system moves the
thread to blocked state until the I/O operations gets completed.
Terminated State:
After successful completion of the execution the thread in runnable state enters the
terminated state.
Thread
Synchronization
Definition: Threads Synchronization
Thread synchronization is the concurrent execution of two or more threads that share
critical resources.
When two or more threads need to use a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process of ensuring single thread
access to a shared resource at a time is called synchronization.
Why use Synchronization
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block
2. Cooperation (Inter-thread communication in java)
Java synchronized method
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task
Syntax to use synchronized method:
Access_modifier synchronized return_type method_name(parameters)
{ …….. }
Example of java synchronized method:
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(){
t.printTable(100);
}
}
public 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
5
10
15
20
25
100
200
300
400
500
Inter-Thread Communication
Inter-Thread Communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
Definition: Inter-Thread Communication Inter-thread communication is a
mechanism in which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical section to be
executed.
It is implemented by following methods of Object class and all these methods can be
called only from within a synchronized context.
S.No Method and Description
1. public final void wait() throws InterruptedException
Causes the current thread to wait until another thread invokes the notify().
2. public final void wait(long timeout) throws InterruptedException
Causes current thread to wait until either another thread invokes the
notify () method or the notifyAll () method for this object, or a specified
amount of time has elapsed.
Parameters:
timeout − the maximum time to wait in milliseconds.
3. public final void notify()
Wakes up a single thread that is waiting on this object's monitor.
4. Public final void notifyAll()
Wakes up all the threads that called wait( ) on the same object.
Example Program:
class Account
{
double balance = 10000.00;
synchronized public double withdraw( double wamt )
{
System.out.println(" Withdraw process starts ");
System.out.println(" Before Withdraw: "+balance);
if(balance < wamt)
{
System.out.println(" Sorry insufficient balance waiting for deposit ");
try
{
wait(); // if any thread calling wait() then it will release the lock in fraction of seconds and
goes to wait() state life long until notify() method calls
// wait(1000); if you want to wait for some particular amount of time
}
catch( InterruptedException e )
{
e.printStackTrace();
}
}
balance = balance - wamt;
System.out.println(" After Withdraw: " + balance);
return wamt;
}
synchronized public void deposit( double damt )
{
System.out.println("\n\n Deposit process starts: ");
System.out.println(" Before Deposit : "+balance);
balance = balance + damt;
System.out.println(" After Deposit : "+balance);
notify();
// notifyAll(); // if you have multiple threads
}
}
public class Test extends Thread
{
public static void main(String args[]) throws InterruptedException
{
final Account acc = new Account();
new Thread()
{
public void run()
{
acc.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
acc.deposit(5000);
}
}.start();
}
}
Output
Creating a Thread
In Java we can implement the thread programs using two approaches -
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.
The run () method is the most important method in any threading program. By using this
method the thread's behaviour can be implemented. The run method can be written as
follows
Extending Thread Class
The Thread class can be used to create a thread. Using the extend keyword your class
extends the Thread class for creation of thread. For example if I have a class named A
then it can be written as
class A extends Thread
Constructor of Thread Class:
o Thread()
o Thread(String s)
o Thread (Runnable obj)
o Thread(Runnable obj, String s);
Various commonly used methods during thread programming are as given below -
Example Program:
class MyThread extends Thread doin
{
public void run()
{
System.out.println("Thread is created!!!");
}
}
class ThreadProg
{
public static void main(String args[])
{
MyThread t=new MyThread();
t.start();
}
}
Output:
Multithreading
Multithreading in Java is a process of executing multiple threads simultaneously.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
Example Program:
Thread Priorities
Priority of a thread describes how early it gets execution and selected by the thread
scheduler.
It holds the minimum priority that can be given to a thread. The value for this is 1.
}
}
th.stop();
By this statement the thread enters in a dead state. From stopping state a thread can never
return to a runnable state.
‘• Blocking a thread: A thread can be temporarily stopped from running. This is called
blocking or suspending of a thread. Following are the ways by which thread can be blocked
1. sleep()
By sleep method a thread can be blocked for some specific time. When the specified time
gets elapsed then the thread can return to a runnable state.
2. suspend()
By suspend method the thread can be blocked until further request comes. When the resume()
method is invoked then the thread returns to a runnable state.
3. wait()
The thread can be made suspended for some specific conditions. When the notify method is
called then the blocked thread returns to the runnable state.
• The difference between the suspending and stopping thread is that if a thread is
suspended then its execution is stopped temporarily and it can return to a runnable state. But
in case, if a thread is stopped then it goes to a dead state and can never return to runnable
state.
Resuming a thread: The resume() method is only used with suspend() method. This method
is only to resume a thread which was suspended using suspend() method. The syntax is -
Example Program
Thread thrd;
boolean suspended;
boolean stopped;
MyThread(String name) {
suspended = false;
stopped = false;
thrd.start();
try {
System.out.print(".");
Thread.sleep(50);
synchronized (this) {
while (suspended)
wait();
if (stopped)
break;
stopped = true;
suspended = false;
notify();
suspended = true;
suspended = false;
notify();
}
}
Thread.sleep(100);
mt.suspend();
Thread.sleep(100);
mt.resume();
Thread.sleep(100);
mt.suspend();
Thread.sleep(100);
mt.resume();
Thread.sleep(100);
mt.stop();
}
Wrappers
Wrapper classes are those classes that allow primitive data types to be accessed as
objects.
The wrapper class is one kind of wrapper around a primitive data type. The wrapper
classes represent the primitive data types in its instance of the class.
int num=obj.intValue();
str=Integer.toString(int_val)
• For converting the string to numerical value the parseInt or parseLong methods can be used.
String str="100";
Autoboxing
Definition: An automatic conversion of primitive data type into equivalent wrapper type is
called as autoboxing.
Example Program
class AutoboxExample
{
public static void main(String args[])
{
//auto-boxing, an int is boxed into Integer object
Integer obj = 111;
//unboxing
int val = obj.byteValue();
System.out.println("Object value = "+obj);
System.out.println("The primitive value = "+val);
}
}
Output
}
System.out.println(i);
}
}
}
class TMethods
{
public static void main(String args[])
{
Th t1=new Th();
Th t2=new Th();
/*System.out.println("ID="+t1.getId());
System.out.println("Name of Thread is "+t1.getName());
t1.setName("Balamurugan");
System.out.println("Name of Thread after changing its name "+t1.getName());
System.out.println("Priority of Thread is "+t1.getPriority());
t1.setPriority(10);
System.out.println("Priority of Thread after changing "+t1.getPriority());*/
t1.start();
try{
t1.join();
}
catch(Exception e)
{
}
System.out.println("Thread1 Status:"+t1.isAlive());
t2.start();
}
}