Unit-3 Exception Handling, Multi Threading

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

UNIT-3

EXCEPTION HANDLING, MULTI THREADING


Concepts of Exception handling – Types of exceptions – Creating own
exception – Concepts of Multithreading – creating multiple threads –
Synchronization – Inter thread communication. Enumeration:
Autoboxing – Generics.
CONCEPTS OF EXCEPTION HANDLING
The exception handling in java is one of the powerful mechanisms to
handle the runtime errors so that normal flow of the application can be
maintained.
What is Exception?
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is
an object which is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the
application. Exception normally disrupts the normal flow of the application that
is why we use exception handling.
Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there is 10 statements in your program and there occurs an exception at
statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not
run. If we perform exception handling, rest of the exception will be executed.
That is why we use exception handling in java.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem says
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 that extend Throwable class except Runtime Exception and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend Runtime Exception are known as unchecked exceptions
e.g. Arithmetic Exception, NullPointer Exception, ArrayIndexOutOfBounds
Exception etc. Unchecked exceptions are not checked at compile-time rather they
are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemory Error, VirtualMachine Error, Assertion
Error etc. Common scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can
occur. They are as follows:
3) Scenario where Arithmetic Exception occurs
If we divide any number by zero, there occurs an Arithmetic Exception.
int a=50/0; //Arithmetic Exception
4) Scenario where Null Pointer Exception occurs
If we have null value in any variable, performing any operation by the
variable occurs an Null Pointer Exception.
String s=null;
System.out.println(s.length());//Null Pointer Exception
3)Scenario where Number Format Exception occurs
The wrong formatting of any value, may occur Number Format Exception.
Suppose I have a string variable that have characters, converting this
variable into digit will occur Number Format Exception.
String s="abc";
int i=Integer.parseInt(s);//Number Format Exception
4)Scenario where ArrayIndexOutOfBounds Exception occurs
If you are inserting any value in the wrong index,
it would result ArrayIndexOutOfBounds Exception as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

JAVA EXCEPTION HANDLING KEYWORDS


There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
JAVA TRY BLOCK
Java try block is used to enclose the code that might throw an exception. It
must be used within the method.
Java try block must be followed by either catch or finally block
Syntax of java try-catch
try
{
//code that may throw exception
}
catch(Exception_type obj)
{

JAVA CATCH BLOCK


Java catch block is used to handle the Exception. It must be used after the try
block only. You can use multiple catch block with a single try.
EXAMPLE PROGRAM
public class Testtrycatch2
{
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 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 must be followed by try or catch block
JAVA THROW KEYWORD
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

EXAMPLE PROGRAM
class ExceptionThrowDemo
{
public static void main(String args[ ])
{int a=Integer.parseInt(args[0]); try
{
if(a>10)
{
throw new ArithmeticException("A is greater than 10");
}
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("Program End");
}
}

JAVA THROWS
 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 NullPointer
Exception, it is programmers fault that he is not performing check up
before the code being used

Syntax:
return_type method_name() throws exception_class_name
{
...
}

EXAMPLE:
import java.io.IOException;
class Testthrows1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
Try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
}
public static void main(String args[])
{
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
CONCEPTS OF MULTITHREADING
Multithreading is a powerful programming tool that makes java distinctly different
from its fellow programming languages.
 The ability of executing several programs simultaneously is called
Multitasking.
 The ability of executing several processes simultaneously is called
Multithreading.

THREAD
 A Thread is simple process
 A thread has a beginning, a body, and an end, and executes command
sequentially.
 The entire main program can be called single-threaded programs.
 Since threads in java share the same memory space, they are
known as Lightweight threads Or Lightweight processes.
‘Threads running in parallel’ does not mean they are running at the same time.
USES OF MULTITHREADING
 Enables programmers to do multi things at a time.
 A long program can be divided into threads and execute them in parallel.
 Extensively used in java-enabled browsers as Hot. Java

DIFFERENCE BETWEEN MULTITASKING AND MULTITHREADING

Sl. No MULTITHREADING MULTITASKING


1 It is a programming concept in which a An operating system concept in which
program is divided into two or more multiple tasks are performed
threads executed in parallel simultaneously
2 It supports execution of multiple It supports execution of
process simultaneously multiple program
3 The processor has to switch between simultaneously
The processor has to switch
different parts or threads of a program between different programs.

4 Highly efficient Less efficient compared to


multithreading.
5 A thread is the smallest A program is the smallest
unit in multithreading unit in multitasking
6 Helps in developing efficient programs Helps in developing efficient OS.
7 It is cost-effective in Expensive in case of context switching.
case of context switching
CREATING THREADS
 Threads are implemented in the form of objects that contain a method called
run().
 The run( ) method is the heart and soul of any thread.
 It makes up the entire body of the method.
 It’s the only method in which the thread’s behavior can be implemented.
 The run( ) method should be invoked by an object of the concerned thread.
 This can be done by creating a thread and initializing it with the help of
another method called start( ) .
Syntax:
Public void run( )
{
……………….. (Statements)
………………..
}
LIFE CYCLE OF A THREAD
During the lifetime of a thread, it can enter many states as,
1. Newborn state.
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

NEWBORN STATE:
5. When we create the Thread object, the thread is born and is said to be in
Newborn state.
6. At this state we can do only one of the following,
7. Schedule it for running using start( ) method.
8. Kill it using stop( ) method.
RUNNABLE STATE:
5. The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor.
6. The process of assigning time to threads is known as time- slicing.
7. The first-come, first-serve manner is used here.
8. If we want to relinquish control to another thread to equal the priority
before it comes, we can use the yield( ) method
BLOCKED STATE:
3. A thread is said to be blocked when it is prevented from entering into
the runnable state and the running state.
4. A blocked thread is considered “not runnable” but not dead, and is fully
qualified to run again.
DEAD STATE:
4. A running thread ends its life when it has completed executing its run( )
method.
5. It is natural death.
6. A thread can be killed as soon as it is born, or while running or even
when it is in “not runnable “condition.
CREATING A NEW THREAD:
There are two ways,
1. by creating a thread class - Define a class that extends Thread class and
override its run( ) Method.
2. By converting a class to a thread – Define a class that implements Runnable
interface.
EXTENDING THE THREAD CLASS:
 We can extend the class by using java.lang.Thread.
 This gives access to all thread methods directly.
It includes the following:
1. Declare the class as extending the Thread class.
2. Implement the run( ) method for executing the Thread.
3. Create a thread object and class the start( ) method to initiate thread execution.
DECLARING THE CLASS:
The Thread class can be extended as follows:
class MyThread extends Thread
{
…………………
………………....
}
Now we have a new type of thread MyThread.
STARTING A NEW THREAD:
The syntax for creating and running an instance of the thread is as follows,
MyThread t1 = new
MyThread();
t1.start();
First line – instantiates a new object of class MyThread.
Second Line - calls the start( ) method causing the thread to move into the
runnable state.
EXAMPLE PROGRAM:
import java.lang.*;
class MyThreadA extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("MyThread 1 :"+i);
}
}
}
class MyThreadB extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("MyThread 2 :"+i);
}
}
}
public class ThreadExample
{
public static void main(String args[]) throws Exception
{
MyThreadA m1=new MyThreadA();
MyThreadB m2=new MyThreadB();
m1.start();
m2.start();
}
}
SYNCHRONIZATION IN JAVA
Synchronization in Java is the capability to control the access of multiple threads
to any shared resource.

Java Synchronization is better option where we want to allow only one thread to
access the shared resource.

Why use Synchronization?


The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. It can be achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization
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.

//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

Synchronized Block in Java


Synchronized block can be used to perform synchronization on any specific
resource of the method.

Suppose we have 50 lines of code in our method, but we want to synchronize only
5 lines, in such cases, we can use synchronized block.

If we put all the codes of the method in the synchronized block, it will work same
as the synchronized method.

Points to remember for Synchronized block


1. Synchronized block is used to lock an object for any shared resource.
2. Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


synchronized (object reference expression) {
//code block
}
Example of synchronized block
Let's see the simple example of synchronized block.
Program of synchronized block
class Table{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
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 TestSynchronizedBlock1{
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

Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on
object.

Example of static synchronization


In this example we are applying synchronized keyword on the static
method to perform static synchronization.
Example 1:
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends Thread{
public void run(){
Table.printTable(1);
}
}
class MyThread2 extends Thread{
public void run(){
Table.printTable(10);
}
}
class MyThread3 extends Thread{
public void run(){
Table.printTable(100);
}
}
class MyThread4 extends Thread{
public void run(){
Table.printTable(1000);
}}
public class TestSynchronization4{
public static void main(String t[]){
MyThread1 t1=new MyThread1();
MyThread2 t2=new MyThread2();
MyThread3 t3=new MyThread3();
MyThread4 t4=new MyThread4();
t1.start();
t2.start();
t3.start();
t4.start();
}
}

Output:
Compile by: javac TestSynchronization4.java
Run by: java TestSynchronization4

1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

INTER THREAD COMMUNICATION


Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate with each other.
Cooperation (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:

 wait()
 notify()
 notifyAll()

1) wait() method
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.
The current thread must own this object's monitor, so it must be called
from the synchronized method only otherwise it will throw exception.

Method Description
public final void Waits until object is notified.
wait()throws’
InterruptedException
public final void wait(long timeout)throws Waits for the specified amount of time.
InterruptedException

2) notify() method
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.
Syntax:
Public final void notify()

3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:
public final void notifyAll()

Understanding the process of inter-thread communication


1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified
state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the
monitor state of the object.
wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by after the specified amount of time,
notify() or notifyAll() methods sleep is completed.
Example of inter thread communication in java
Let's see the simple example of inter thread communication.
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{
wait();
}
catch(Exception e){
}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){
c.withdraw(15000);} }.start();
new Thread(){
public void run(){
c.deposit(10000);}
}.start();
}}
Output:
Going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

ENUMERATION
Enumerations make for clearer and more readable code, particularly when
meaningful names are used. The benefits of using enumerations include: Reduces
errors caused by transposing or mistyping numbers. Makes it easy to change
values in the future.

AUTOBOXING
Converting a primitive value into an object of the corresponding wrapper class
is called auto boxing. For example, converting int to Integer class. The Java
compiler applies autoboxing when a primitive value is:
 Passed as a parameter to a method that expects an object of the
corresponding wrapper class.
 Assigned to a variable of the corresponding wrapper class.

Advantage of Autoboxing and Unboxing:


 No need of conversion between primitives and Wrappers manually so
less coding is required.
Simple Example of Autoboxing in java:
class BoxingExample1{
public static void main(String args[]){
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
System.out.println(a2+" "+a3);
}
}
Output: 50 5
Unboxing:
Converting an object of a wrapper type to its corresponding primitive value is
called unboxing.
For example, conversion of Integer to int. The Java compiler applies unboxing
when an object of a wrapper class is:
Passed as a parameter to a method that expects a value of the corresponding
primitive type.
Assigned to a variable of the corresponding primitive type
Simple Example of Unboxing in java:
The automatic conversion of wrapper class type into corresponding primitive
type, is known as Unboxing.
Let's see the example of unboxing:
class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}
Output:
50

GENERICS
The Java Generics programming is introduced in J2SE 5 to deal with type-safe
objects.
Before generics, we can store any type of objects in collection i.e. non-generic.
Now generics, forces the java programmer to store specific type of objects.
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety: We can hold only a single type of objects in generics. It
doesn’t allow to store other objects.
2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList(); list.add("hello");
String s = (String) list.get(0);//typecasting After Generics, we don't need to
typecast the object.
List<String> list = new ArrayList<String>(); list.add("hello");
String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem
will not occur at runtime.
The good programming strategy says it is far better to handle the problem at
compile time than runtime.
List<String> list = new ArrayList<String>(); list.add("hello");
list.add(32);//Compile Time Error
Syntax to use generic collection
ClassOrInterface<Type>
Example to use Generics in java
ArrayList<String>
EXAMPLE OF GENERICS IN JAVA
Here, we are using the ArrayList class, but you can use any collection class such as
ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

import java.util.*;
class TestGenerics1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
element is: jai rahul
jai
GENERIC CLASS
A class that can refer to any type is known as generic class. Here, we are using T
type parameter to
create the generic class of specific type.
Let’s see the simple example to create and use the generic class.
Creating generic class:

class MyGen<T>{ T obj;


void add(T obj){this.obj=obj;} T get(){return obj;}
}
The T type indicates that it can refer to any type (like String, Integer, Employee
etc.). The type youspecify for the class, will be used to store and retrieve the data.
Using generic class:
Let’s see the code to use the generic class.

class TestGenerics3{
public static void main(String args[]){ MyGen<Integer> m=new
MyGen<Integer>(); m.add(2);
//m.add("vivek");//Compile time error System.out.println(m.get());
}}
Output: 2
GENERIC METHOD
Like generic class, we can create generic method that can accept any type of
argument.
Let’s see a simple example of java generic method to print array elements. We are
using here E to
denote the element.

public class TestGenerics4{


public static < E > void printArray(E[] elements) {
for ( E element : elements)
{
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] )
{
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[]
charArray = { 'J', 'A', 'V', 'A' };
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
Output:
Printing Integer Array 10
20
30
40
50
Printing Character Array J A V A

You might also like