0% found this document useful (0 votes)
18 views31 pages

Unit - 3

The document discusses concepts related to exception handling and multithreading in Java. It covers exception hierarchy, checked and unchecked exceptions, using try, catch, throw, throws and finally, creating custom exceptions, differences between processes and threads, thread life cycle, creating and interrupting threads, thread priorities, synchronization, and inter-thread communication including the producer-consumer problem. It also provides contact information for Dr. Jayapal.

Uploaded by

Nagalakshmi Uggu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views31 pages

Unit - 3

The document discusses concepts related to exception handling and multithreading in Java. It covers exception hierarchy, checked and unchecked exceptions, using try, catch, throw, throws and finally, creating custom exceptions, differences between processes and threads, thread life cycle, creating and interrupting threads, thread priorities, synchronization, and inter-thread communication including the producer-consumer problem. It also provides contact information for Dr. Jayapal.

Uploaded by

Nagalakshmi Uggu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT-3

Exception handling-Benefits of exception handling,


the classification of exceptions - exception hierarchy,
checked exceptions and unchecked exceptions,
usage of try, catch, throw, throws and finally,
creating own exception subclasses.
Multithreading – Differences between multiple
processes and multiple threads, thread life cycle,
creating threads, interrupting threads, thread
priorities, synchronizing threads, inter-thread
communication, producer consumer problem.

Dr.Jayapal
[email protected]
Exception: An Exception is defined as “an abnormal error condition that arises
during our program execution”
When a Exception occurs in a program, the java interpreter creates an exception
object and throws it out as java exceptions, which are implemented as objects of
exception class. This class is defined in java.lang package
An Exception object contains data members that will store the exact
information about the runtime error (Exception) that has occurred.

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Dr.Jayapal
[email protected]
Dr.Jayapal
[email protected]
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Dr.Jayapal
[email protected]
1.try: The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be followed
by either catch or finally.

The statements that produces exception are identified in the program and the
statements are placed in try block
Syntax:
try
{
//Statements that causes Exception
}
2.catch :The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed by finally
block later.

The catch block is used to process the exception raised. The catch block is placed
immediately after the try block.
Syntax:
catch(ExceptionType ex_ob)
{
//Statements that handle Exception
Dr.Jayapal
} [email protected]
3.finally:finally creates a block of code that will be executed after a try/catch block
has completed. The finally block will execute whether or not an exception is thrown. If
an exception is thrown, the finally block will execute even if no catch statement
matches the exception.
Syntax:
finally
{
// statements that executed before try/catch
}

4.throw:The "throw" keyword is used to throw an exception.


It is possible to create a program that throws an exception explicitly, using the “throw
” statement.
Syntax: throw throwable_instance;
Here throwable_instance must be an object type of Throwable class or subclass of
Throwable. There are two ways to obtain a Throwable objects
1. using parameter into a catch clause
2. Crating one with the new operator
Dr.Jayapal
[email protected]
5.throws:
If a method is capable of causing an exception that it doen’t handle, it must specify
the behaviour to the callers of the method can guard themselves against that ex ce
ptin. This can be don’t by throws statement in the methods declarations.
A throws lists the types of exceptions that a method might throw.
Syntax: return_ type method_name(parameter-list)throws exception-list
{
//method body
}
Here, exception-list is a comma-separated list of the exception that a method can
throw.

Dr.Jayapal
[email protected]
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...

Dr.Jayapal
[email protected]
UserDefined Exceptions
It is possible to create our own exception types to handle situations specific to our
application. Such exceptions are called User-defined Exceptions. User defined exceptions
are created by extending Exception class. The throw and throws keywords are used while
implementing user-defined exceptions.
***Common Example for try , catch, throw , throws, finally and Userdefined
exception:***

import java.io.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}

Dr.Jayapal
[email protected]
Class Test
{ public static void main(String ar[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter marks”);
try
{
int marks=Integer.parseInt(br.readLine());
if(marks>100)
{
throw new MyException(“Greater than 100”);
}
System.out.println(“Marks=”+marks);
}
catch(MyException e)
{
System.out.println(e.getMessage());
}
finally
{ System.out.println(“completed”);
}
}
Dr.Jayapal
} [email protected]
output-1:
Enter marks
99
Marks=99
completed

output-2:
Enter marks
101
Greater than 100
completed

Dr.Jayapal
[email protected]
Nested Try
A try block is placed inside the block of another try
block is termed as Nested try block statements. If any
error statement is in outer try block , it goes to the
corresponding outer catch block. If any error
statement is in inner try block first go to the inner
catch block. If it is not the corresponding exception
next goes to the outer catch, which is also not
corresponding exception then terminated.

Dr.Jayapal
[email protected]
class NestedTry
{
public static void main(String args[])
{
try
{
int a=args.length;//‘a’ stores no of command line args
int b=42/a; //if a=0 it is Arithemetic Exception
try
{
if(a==1)
a=a/(a-a);

if(a==2)
{
int c[]={3};
c[20]=40;
}
}// end of inner try

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index exceeds");
}

}//end of outer try

catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception");
}

}//end main
} Dr.Jayapal
[email protected]
Multiple Catch Statements
Multiple catch statements handle the situation where more than one exception
could be raised by a single piece of code. In such situations specify two or more
catch blocks, each specify different type of exception.

class MultiCatch
{
public static void main(String args[])
{
try
{
int a=args.length;
int b=42/a;
int c[]={3};
c[20]=40;
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
} Dr.Jayapal
[email protected]
Thread:
Thread is a sequence of instructions that is executed to define a unique
flow of control. It is the smallest unit of code.
or
A thread in Java is the direction or path that is taken while a program is
being executed. Generally, all the programs have at least one thread,
known as the main thread, that is provided by the JVM or Java Virtual
Machine at the starting of the program’s execution
Multiprogramming is a form of parallel processing in which several
programs are run at the same time on a uniprocessor.Since there is only
one processor, there can be no true simultaneous execution of different
programs. Instead, the operating system executes part of one program,
then part of another, and so on. To the user it appears that all programs are
executing at the same time.
Multitasking, in an operating system, is allowing a user to perform more
than one computer task (such as the operation of an application program)
at a time. The operating system is able to keep track of where you are in
these tasks and go from one to the other without losing information
Dr.Jayapal
[email protected]
Multithreading is the ability of a program to manage its use by more than
one thread at a time .Dispatchable atomic units of the program are
executing simultaneously.

Multithreaded applications deliver their potent power by running many


threads concurrently within a single program. From a logical point of view,
multithreading means multiple lines of a single program can be executed at
the same time, however, it is not the same as starting a program twice and
saying that there are multiple lines of a program being executed at the
same time. In this case, the operating system is treating the programs as
two separate and distinct processes.

Dr.Jayapal
[email protected]
Differences between multi threading and multitasking(Multi process):

MULTI THREADING MULTI TASKING


1). More than one thread running simultaneously 1). More than one process running
simultaneously
2).it is a light-weight process. 2). It is a heavy-weight process.
3). Threads are divided into sub threads 3). Process is divided into threads.
4). Within the process threads are 4). Inter process communication is difficulty
communicated.
5). Context switching between threads is 5). Context switching between process is
cheaper. costly
6). It is controlled by Java(JVM) 6). It is controlled by operating System.
7).It is a specialized form of multi tasking 7). It is a generalized form of multi
threading.

Dr.Jayapal
[email protected]
Lifecycle of a Thread
During the lifetime of a thread, there are many states it can enter. They include:
1. NewBorn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State

Dr.Jayapal
[email protected]
NewBorn State:
When we create a thread object, the thread is born and is said to be in newborn state.
The thread is not yet scheduled for running. At t his state, we can do only one of the
following things with it:
Schedule it for running using start() method
Kill it using stop() method
Runnable State:
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. If we want a thread to relinquish control to another thread
to equal priority before its turn comes, we can do so by using the yield()
Running State:
Running means that the processor has given its time to the thread for its execution. The
thread runs until it relinquishes control on its own or it is preempted by a higher priority
thread.
Blocked State:A thread is said to be blocked when it is prevented from entering into the
runnable state and subsequently the running s tate. This happens when the thread is
suspended, sleping, or waiting in order to satisfy certain requirements. A blocked thread
is considered “not runnable” but not dead and therefore fully qualified to run again.
Dead State:
Every thread has a lifecycle. A running thread ends its life when it has completed
executing its run() method. It is natural death. However, we can kill it by sending the stop
message to it at any state thus causing a premature death to it. It is done by stop()
method. Dr.Jayapal
[email protected]
Creating a thread
Java defines two ways by which a thread can be created.
1. By implementing the Runnable interface.
2. By extending the Thread class

Implementation of thread

Extends Implements

Thread (class)
Runnable (interface)

Run() method

Dr.Jayapal
[email protected]
Implementing Thread by Runnable Interface:
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,

public void run()

run() method introduces a concurrent thread into your program. This thread will end
when run() returns.specify the code for your thread inside run() method.
run() method can call other methods, can use other classes and declare variables just
like any other normal method.

Write a Java Program to implement simple Thread

Dr.Jayapal
[email protected]
Implementing Thread by Extending Thread class
The second way to create a thread is to create a new class that extends Thread, and
then to create an instance of that class. The extending class must override the run( )
method, which is the entry point for the new thread. It must also call start( ) to begin
execution of the new thread.

Write a Java Program to implement simple Thread by extending Thread class

Java program to implement two threads in parallel

Dr.Jayapal
[email protected]
Thread Priorities:
Every thread has a priority that helps the operating system determine the
order in which threads are scheduled for execution. In java thread priority
ranges between,
MIN-PRIORITY (a constant of 1)
MAX-PRIORITY (a constant of 10)
By default every thread is given a NORM-PRIORITY(5). The main thread
always have NORM-PRIORITY.
Threads with higher priority are more important to a program and should
be allocated processor time before lower-priority threads. However,
thread priorities cannot guarantee the order in which threads execute and
very much platform dependent.

Dr.Jayapal
[email protected]
synchronizing threads
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.
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.

Dr.Jayapal
[email protected]
Types of Synchronization
• Process Synchronization
•Thread Synchronization

Thread Synchronization
There are two types of thread synchronization mutual
exclusive and inter-thread communication.
1.Mutual Exclusive
i)Synchronized method.
ii)Synchronized block.
ii)StaticSynchronization
2.Cooperation (Inter-thread communication in java)

Dr.Jayapal
[email protected]
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

Dr.Jayapal
[email protected]
Java Synchronized Method
A method can be declared as Synchronized by
the key word synchronized.
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.

Dr.Jayapal
[email protected]
Synchronized Block in Java
Synchronized block can be used to perform
synchronization on any specific resource of
the method.

If there are many lines of code in a method,


but need to synchronize only 5 lines, in such
cases use synchronized block.

Syntax
synchronized (object reference expression) {
//code block
} Dr.Jayapal
[email protected]
Static Synchronization
any static method is synchronized then the
lock will be on the class not on object.

Dr.Jayapal
[email protected]
Interrupting threads:
Stopping a thread: A thread can be stopped from running further by issuing the
following statement-
1.Use of stop() Method
The stop() method kills the thread on execution
By this statement the thread enters in a dead state. From stopping state a thread can
never return to a runnable state.
2. 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-
a)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.
b)suspend( ) By suspend method the thread can be blocked until further request
comes. When the resume() method is invoked then the returns to a runnable state
c)wait():The thread can be made suspended for some specific conditions. When the
d)notify() method is called then tha 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.

Dr.Jayapal
[email protected]
Producer-Consumer problem

There is one Producer in the producer-


consumer problem, Producer is producing
some items, whereas there is one Consumer
that is consuming the items produced by the
Producer. The same memory buffer is shared
by both producers and consumers which is of
fixed-size.

Dr.Jayapal
[email protected]

You might also like