Sunteți pe pagina 1din 21

Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING

UNIT - 5

Q) What Is an Exception? Give types of exceptions.


An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. Java Exceptions are basically Java
objects.

When an error occurs within a method, the method creates an object and hands
it off to the runtime system. 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.

After a method throws an exception, the runtime system attempts to find


something to handle it. The list of methods is known as the call stack. The runtime
system searches the call stack for a method that contains a block of code that can
handle the exception. This block of code is called an exception handler. The search
begins with the method in which the error occurred and proceeds through the call
stack in the reverse order in which the methods were called. When an appropriate
handler is found, the runtime system passes the exception to the handler. An
exception handler is considered appropriate if the type of the exception object thrown
matches the type that can be handled by the handler.

The exception handler chosen is said to catch the exception. If the runtime
system exhaustively searches all the methods on the call stack without finding an
appropriate exception handler, as shown in the next figure, the runtime system (and,
consequently, the program) terminates.

Exceptions in Java are classified on the basis of the exception handled by the java
compiler. Java consists of the following type of built in exceptions:

1
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

Checked and Unchecked Exceptions


a) Checked exceptions are subclass’s of Exception excluding class
RuntimeException and its subclasses. Checked Exceptions forces programmers to
deal with the exception that may be thrown. Example: Arithmetic exception. When a
checked exception occurs in a method, the method must either catch the exception
and take the appropriate action, or pass the exception on to its caller.

b) Unchecked exceptions are RuntimeException and any of its subclasses. Class


Error and its subclasses also are unchecked. Unchecked exceptions, however, the
compiler doesn’t force the programmers to either catch the exception or declare it in
a throws clause. In fact, the programmers may not even know that the exception
could be thrown. Example: ArrayIndexOutOfBounds Exception.

10 Q) Give list of checked and unchecked exceptions.


List of Checked Exceptions
Following are the list of various checked exception that defined in the java. lang
package.

Exception Reason for Exception


This Exception occurs when Java run-time system fail to
ClassNotFoundException
find the specified class mentioned in the program
This Exception occurs when you create an object of an
InstantiationException
abstract class and interface
This Exception occurs when you create an object of an
IllegalAccessException
abstract class and interface
2
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

This Exception occurs when the method you call does


NotSuchMethodException
not exist in class

List of Unchecked Exceptions


Exception Reason for Exception
These Exception occurs, when you divide a number
ArithmeticException
by zero causes an Arithmetic Exception
These Exception occurs, when you try to assign a
ClassCastException reference variable of a class to an incompatible
reference variable of another class
These Exception occurs, when you assign an array
ArrayStoreException which is not compatible with the data type of that
array
These Exception occurs, when you assign an array
ArrayIndexOutOfBoundsExcepti
which is not compatible with the data type of that
on
array
These Exception occurs, when you try to implement an
NullPointerException application without referencing the object and
allocating to a memory
These Exception occurs, when you try to convert a
string variable in an incorrect format to integer
NumberFormatException
(numeric format) that is not compatible with each
other

11 Q) Explain how to handle exceptions in java.


Java exception handling mechanism enables you to catch exceptions in java using try,
catch, finally blocks.
Exceptions are handled using a try-catch-finally construct, which has the Syntax
try
{
<code>
}
catch (<exception type1> <parameter1>)
{
// 0 or more <statements>
}
finally
{
3
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

// finally block <statements>


}

Try Block
Write the code where there is a possible to occur a run-time error in the program. If
there is an exception then try throws an exception to it’s corresponding run-time error
catch block. If no exception occurs the execution proceeds with the finally block else it
will look for the matching catch block to handle the error. Again if the matching catch
handler is not found execution proceeds with the finally block and the default
exception handler throws an exception. If an exception is generated within the try
block, the remaining statements in the try block are not executed.

Catch Block
Exceptions thrown during execution of the try block can be caught and handled in a
catch block. On exit from a catch block, normal execution continues and the finally
block is executed
(Though the catch block throws an exception).

Finally Block
A finally block is always executed, regardless of the cause of exit from the try block,
or whether any catch block was executed. Generally finally block is used for freeing
resources, cleaning up, closing connections etc. If the finally clock executes a control
transfer statement such as a return or a break statement, then this control statement
determines how the execution will proceed regardless of any return or control
statement present in the try or catch.

4
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

12 Q) what are rules for try, catch and finally block. Give one
example.
1. For each try block there can be zero or more catch blocks, but only one finally
block.
2. The catch blocks and finally block must always appear in conjunction with a try
block.
3. A try block must be followed by either at least one catch block or one finally block.
4. The order exception handlers in the catch block must be from the most specific
exception.

Let’s examine each of these in detail.


public class DivideException1
{
public static void main(String[] args)
{ division(100,0);
System.out.println("Main Program Terminating");
}
public static void division(int x, int y)
{
int z=-1;
System.out.println("Computing Division.");
Try
{ z = x/y;
System.out.println("Result is : "+z);
}
catch(Exception e)
{
System.out.println("Exception : "+ e.getMessage());
}
finally
{
if(z!= -1){
System.out.println("Finally Block Executes");
System.out.println("Result : "+ z);
}

5
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

else{
System.out.println("Finally Block Executes. Exception Occurred");
}
}
}
}

Output
Computing Division
Exception: / by zero
Finally Block Executes. Exception Occurred
Main Program Terminating

As shown above when the divide by zero calculation is attempted, an


ArithmeticException is thrown. And program execution is transferred to the catch
statement. Because the exception is thrown from the try block, the remaining
statements of the try block are skipped. The finally block executes.

13 Q) How to handle multiple exceptions in java?


In java when we handle the exceptions then we can have multiple catch blocks for a
particular try block to handle many different kind of exceptions that may be
generated while running the program i.e. you can use more than one catch clause in a
single try block however every catch block can handle only one type of exception.
This mechanism is necessary when the try block has statement that raises different
type of exceptions.
The syntax for using this clause is given below:-
try
{
statement -1;
statement -2;
----------
statement -n;

}
catch(<exceptionclass_1>,<obj1>)

6
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

{
//statements to handle the exception
}
catch(<exceptionclass_2>,<obj2>)
{
//statements to handle the exception
}
catch(<exceptionclass_N>,<objN>)
{
//statements to handle the exception
}

When an exception is thrown, normal execution is suspended. The runtime system


proceeds to find a matching catch block that can handle the exception. If no handler is
found, then the exception is dealt with by the default exception handler at the top
level.

Let’s see an example given below which shows the implementation of multiple catch
blocks for a single try block.

7
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

public class Multi_Catch


{
public static void main (String args[])
{
int array[]={20,10,30};
int num1=15,num2=0;
int res=0;

try
{
res = num1/num2;
System.out.println("The result is" +res);

for(int i=2;i>=0; i--)


{
System.out.println("The value of array are"
+array[i]);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error. Array is out of Bounds");
}

catch (ArithmeticException e)
{
System.out.println ("Can't be divided by Zero");
}
}
}

OUTPUT:
C:\Raghu\>javac Multi_Catch.java
C:\Raghu\>java Multi_Catch
Can't be divided by Zero
8
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

In this example we have used two catch clause catching the exception
ArrayIndexOutOfBoundsException and ArithmeticException in which the
statements that may raise exception are kept under the try block. When the program
is executed, an exception will be raised. Now that time the first catch block is skipped
and the second catch block handles the error.

14Q) How to create user defined exceptions in java?


sometimes you may occasionally need to throw your own exception i.e. if you
encounter a situation where none of those exception describe your exception
accurately or if you can't find the appropriate exception in the Java API, you can code
a class that defines an exception that is more appropriate and that mechanism of
handling exception is called Custom or User Defined Exception.

In Java API all exception classes have two type of constructor. First is called
default constructor that doesn't accept any arguments. Another constructor accepts a
string argument that provides the additional information about the exception. So in
that way the Custom exception behaves like the rest of the exception classes in Java
API.
There are two primary use cases for a custom exception.
• Your code can simply throw the custom exception when something goes
wrong.
• You can wrap an exception that provides extra information by adding your own
message.
The code of a Custom exception:
public class ExceptionClassName extends
Exception
{
public ExceptionClassName(){ }
public ExceptionClassName(StringMessage)
{
super(message);
}
}

// This program creates a custom exception type

9
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

class MyException extends Exception


{
private int detail;
MyException(int a)
{
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}

class ExceptionDemo
{
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
if (a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}

public static void main(String args[])


{
try
{
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

Q) what is a multithread? How threads improve performance of


java?
Multithreading refers to two or more tasks executing concurrently within a single
program. A thread is an independent path of execution within a program. Many
10
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

threads can run concurrently within a program. Every thread in Java is created and
controlled by the java.lang.Thread class. A Java program can have many threads,
and these threads can run concurrently, either asynchronously or synchronously.
Multithreading has several advantages over Multiprocessing such as;
• Threads are lightweight compared to processes
• Threads share the same address space and therefore can share both data and code
• Context switching between threads is usually less expensive than between processes
• Cost of thread intercommunication is relatively low that that of process
intercommunication
• Threads allow different tasks to be performed concurrently.
The following figure shows the methods that are members of the Object and
Thread Class.

Thread Creation
There are two ways to create thread in java;
• Implement the Runnable interface (java.lang.Runnable)
• By Extending the Thread class (java.lang.Thread)

Implementing the Runnable Interface


The Runnable Interface Signature
public interface Runnable {
void run();
}
One way to create a thread in java is to implement the Runnable Interface and then
instantiate an object of the class. We need to override the run() method into our class
which is the only method that needs to be implemented. The run() method contains
the logic of the thread.
The procedure for creating threads based on the Runnable interface is as
follows:
1. A class implements the Runnable interface, providing the run() method that will be
executed by the thread. An object of this class is a Runnable object.

11
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

2. An object of Thread class is created by passing a Runnable object as argument to


the Thread constructor. The Thread object now has a Runnable object that
implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step.
The start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by
throwing an uncaught exception.
Below is a program that illustrates instantiation and running of threads using the
runnable interface instead of extending the Thread class. To start the thread you need
to invoke the start() method on your object.
class RunnableThread implements Runnable {

Thread runner;
public RunnableThread() {
}
public RunnableThread(String threadName) {
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}

public class RunnableExample {

public static void main(String[] args) {


Thread thread1 = new Thread(new RunnableThread(), "thread1");
Thread thread2 = new Thread(new RunnableThread(), "thread2");
RunnableThread thread3 = new RunnableThread("thread3");
//Start the threads
thread1.start();
thread2.start();
try {
//delay for one second
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
12
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

System.out.println(Thread.currentThread());
}
}
Output
thread3
Thread[thread1,5,main]
Thread[thread2,5,main]
Thread[thread3,5,main]
Thread[main,5,main]private
Extending Thread Class
The procedure for creating threads based on extending the Thread is as follows:
1. A class extending the Thread class overrides the run() method from the Thread
class to define the code executed by the thread.
2. This subclass may call a Thread constructor explicitly in its constructors to initialize
the thread, using the super() call.
3. The start() method inherited from the Thread class is invoked on the object of the
class to make the thread eligible for running.
Below is a program that illustrates instantiation and running of threads by extending
the Thread class instead of implementing the Runnable interface. To start the thread
you need to invoke the start() method on your object.
class XThread extends Thread {

XThread() {
}
XThread(String threadName) {
super(threadName); // Initialize thread.
System.out.println(this);
start();
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}

public class ThreadExample {

public static void main(String[] args) {


Thread thread1 = new Thread(new XThread(), "thread1");

13
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

Thread thread2 = new Thread(new XThread(), "thread2");


// The below 2 threads are assigned default names
Thread thread3 = new XThread();
Thread thread4 = new XThread();
Thread thread5 = new XThread("thread5");
//Start the threads
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
//The sleep() method is invoked on the main thread to cause a one second delay.
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}
Output
Thread[thread5,5,main]
thread1
thread5
thread2
Thread-3
Thread-2
Thread[main,5,main]
12Q) what is synchronization. How to implement it in java?
With respect to multithreading, Synchronization is a process of controlling the access
of shared resources by the multiple threads in such a manner that only one thread
can access a particular resource at a time.
In non synchronized multithreaded application, it is possible for one thread to
modify a shared object while another thread is in the process of using or updating the
object’s value. Synchronization prevents such type of data corruption which may
otherwise lead to dirty reads and significant errors.
Generally critical sections of the code are usually marked with synchronized keyword.
An example of using Thread Synchronization is in “The Producer/Consumer
Model”.

14
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

Locks are used to synchronize access to a shared resource. A lock can be


associated with a shared resource Threads gain access to a shared resource by first
acquiring the lock associated with the object/block of code. At any given time, at most
only one thread can hold the lock and thereby have access to the shared resource. A
lock thus implements mutual exclusion.

The object lock mechanism enforces the following rules of synchronization:


A thread must acquire the object lock associated with a shared resource, before it
can enter the shared
resource. The runtime system ensures that no other thread can enter a shared
resource if another thread already holds the object lock associated with the shared
resource. If a thread cannot immediately acquire
the object lock, it is blocked, that is, it must wait for the lock to become available.
When a thread exits a shared resource, the runtime system ensures that the object lock is
also relinquished.
If another thread is waiting for this object lock, it can proceed to acquire the lock in order to
gain access
to the shared resource.

Classes also have a class-specific lock that is analogous to the object lock. Such
a lock is actually a
lock on the java.lang.Class object associated with the class. Given a class A, the
reference A.class
denotes this unique Class object. The class lock can be used in much the same way as
an object lock to
implement mutual exclusion.
There can be 2 ways through which synchronized can be implemented in Java:
• synchronized methods
• synchronized blocks
Synchronized statements are same as synchronized methods. A synchronized
statement can only be
executed after a thread has acquired the lock on the object/class referenced in the
synchronized statement.

Synchronized Methods

15
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

Synchronized methods are methods that are used to control access to an object. A
thread only executes a synchronized method after it has acquired the lock for the
method’s object or class. .If the lock is already held by another thread, the calling
thread waits. A thread relinquishes the lock simply by returning from the synchronized
method, allowing the next thread waiting for this lock to proceed.

Synchronized methods are useful in situations where methods can manipulate


the state of an object in ways that can corrupt the state if executed concurrently. This
is called a race condition. It occurs when two or more threads simultaneously update
the same value, and as a consequence, leave the value in an undefined or
inconsistent state. While a thread is inside a synchronized method of an object, all
other threads that wish to execute this synchronized method or any other
synchronized method of the object will have to wait until it gets the lock. This
restriction does not apply to the thread that already has the lock and is executing a
synchronized method of the object. Such a method can invoke other synchronized
methods of the object without being blocked. The non-synchronized methods of the
object can of course be called at any time by any thread.

Synchronized Blocks
Static methods synchronize on the class lock. Acquiring and relinquishing a class lock
by a thread in order to execute a static synchronized method, proceeds analogous to
that of an object lock for a synchronized instance method.

A thread acquires the class lock before it can proceed with the execution of any
static synchronized method in the class, blocking other threads wishing to execute
any such methods in the same class. This, of course, does not apply to static, non-
synchronized methods, which can be invoked at any time. Synchronization of static
methods in a class is independent from the synchronization of instance methods on
objects of the class. A sub class decides whether the new definition of an inherited
synchronized method will remain synchronized in the sub class. The synchronized
block allows execution of arbitrary code to be synchronized on the lock of an arbitrary
object.

16
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

The general form of the synchronized block is as follows:


synchronized (<object reference expression>) {
<code block>
}
A compile-time error occurs if the expression produces a value of any primitive
type. If execution of the block completes normally, then the lock is released. If
execution of the block completes abruptly, then the lock is released. A thread can
hold more than one lock at a time. Synchronized statements can be nested.
Synchronized statements with identical expressions can be nested. The expression
must evaluate to a non-null reference value, otherwise, a NullPointerException is
thrown.

The code block is usually related to the object on which the synchronization is
being done. This is the case with synchronized methods, where the execution of the
method is synchronized on the lock of the current object:
public Object method() {
synchronized (this) { // Synchronized block on current object
// method block
}
}
Once a thread has entered the code block after acquiring the lock on the specified
object, no other thread will be able to execute the code block, or any other code
requiring the same object lock, until the lock is relinquished. This happens when the
execution of the code block completes normally or an uncaught exception is thrown.

13Q) Explain in detail about thread life cycle


When you are programming with threads, understanding the life cycle of thread is
very valuable. While a thread is alive, it is in one of several states. By invoking start()
method, it does not mean that the thread has access to CPU and start executing
straight away. Several factors determine how it will proceed.

Different states of a thread are:

17
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

1. New state : After the creations of Thread instance the thread is in this state
but before the start() method invocation. At this point, the thread is considered
not alive.

2. Runnable (Ready-to-run) state: A thread starts its life from Runnable state.
A thread first enters runnable state after the invoking of start() method but a
thread can return to this state after either running, waiting, sleeping or coming
back from blocked state also. On this state a thread is waiting for a turn on the
processor.

3. Running state: A thread is in running state that means the thread is currently
executing. There are several ways to enter in Runnable state but there is only
one way to enter in Running state: the scheduler select a thread from runnable
pool.

4. Dead state: A thread can be considered dead when its run() method
completes. If any thread comes on this state that means it cannot ever run
again.
5. Blocked: A thread can enter in this state because of waiting the resources that
are hold by another thread.
Different states implementing Multiple-Threads are:
As we have seen different states that may be occur with the single thread. A running
thread can enter to any non-runnable state, depending on the circumstances. A
thread cannot enter directly to the running state from non-runnable state; firstly it

18
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

goes to runnable state. Now let’s understand the some non-runnable states which
may be occur handling the multithreads.
• Sleeping: On this state, the thread is still alive but it is not runnable, it might
be return to runnable state later, if a particular event occurs. On this state a
thread sleeps for a specified amount of time. You can use the method sleep( )
to stop the running state of a thread.

static void sleep(long millisecond) throws InterruptedException


• Waiting for Notification: A thread waits for notification from another thread.
The thread sends back to runnable state after sending notification from another
thread.

final void wait(long timeout) throws InterruptedException


final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException

• Blocked on I/O: The thread waits for completion of blocking operation. A


thread can enter on this state because of waiting I/O resource. In that case the
thread sends back to runnable state after availability of resources.

• Blocked for joint completion: The thread can come on this state because of
waiting the completion of another thread.

• Blocked for lock acquisition: The thread can come on this state because of
waiting to acquire the lock of an object.
Methods that can be applied apply on a Thread:

19
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

Some Important Methods defined in java.lang.Thread are shown in the table:


Return
Method Description
Type
currentThrea Returns an object reference to the thread in which it is
Thread
d( ) invoked.
getName( ) String Retrieve the name of the thread object or instance.

start( ) void Start the thread by calling its run method.


This method is the entry point to execute thread, like the
run( ) void
main method for applications.
Suspends a thread for a specified amount of time (in
sleep( ) void
milliseconds).
This method is used to determine the thread is running or
isAlive( ) boolean
not.
activeCount( This method returns the number of active threads in a
int
) particular thread group and all its subgroups.
interrupt( ) void The method interrupts the threads on which it is invoked.
By invoking this method the current thread pause its
yield( ) void
execution temporarily and allow other threads to execute.
This method and join(long millisec) Throws
InterruptedException. These two methods are invoked on
join( ) void
a thread. These are not returned until either the thread
has completed or it is timed out respectively.

Thread Priorities:

20
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5

Every Java thread has a priority that helps the operating system determine the order
in which threads are scheduled.
Java priorities are in the range between
• MIN_PRIORITY (a constant of 1)
• MAX_PRIORITY (a constant of 10).
• By default, every thread is given priority NORM_PRIORITY (a constant of 5).
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.

21

S-ar putea să vă placă și