Академический Документы
Профессиональный Документы
Культура Документы
UNIT - 5
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.
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
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.
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
}
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
}
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
try
{
res = num1/num2;
System.out.println("The result is" +res);
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.
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);
}
}
9
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5
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");
}
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)
11
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5
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());
}
}
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());
}
}
13
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5
14
Object Oriented Programming EXCEPTION HANDLING & MULTITHREADING
UNIT - 5
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 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 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.
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.
• 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
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