unit4 Exception handling & multithreaded Programming
unit4 Exception handling & multithreaded Programming
1) try:
This block applies a monitor on the statements written inside it. If there exist
any exception, the control is transferred to catch or finally block.
Syntax:
try
{
// block of code to monitor for errors
}
2) catch:
This block includes the actions to be taken if a particular exception occurs.
Syntax:
catch(ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
3) finally:
finally block includes the statements which are to be executed in any case, in
case the exception is raised or not.
Syntax:
finally
{
// block of code to be executed before try block ends
}
4) throw:
This keyword is generally used in case of user defined exception, to
forcefully raise the exception and take the required action.
The general form of throw is :
throw new ThrowableInstance;
or
throw throwableinstance;
5) throws:
throws keyword can be used along with the method definition to name the
list of exceptions which are likely to happen during the execution of that method.
In that case , try … catch block is not necessary in the code.
Example:
class XYZ
{
XYZ();
{
// Constructor definition
}
void show() throws Exception
{
throw new Exception()
}
}
Example for Exception handling
classDemoException
{
public static void main(String args[])
{
try
{
int b=8; int c=b/0;
System.out.println(“answer=”+c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
}
}
Inside the standard package java.lang, Java defines several exception classes.
A few have been used by the preceding examples. The most general of these
exceptions are subclasses of the standard type RuntimeException.
These exceptions need not be included in any method‟s throws list, these are
called unchecked exceptions because the compiler does not check to see if a method
handles or throws these exceptions. The unchecked exceptions defined in java.langare
listed inTable1.
Table2 lists those exceptions defined by java.langthat must be includedin
a method‟s throws list if that method can generate one of these exceptions and doesnot
handle it itself. These are called checked exceptions.
Topic 4. Exception Handling & Multithreaded Programming
Table 1. Unchecked Runtime Exceptions
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
Assignment to an array element of an
ArrayStoreException
incompatible type.
ClassCastException Invalid cast.
An attempt is made to use an undefined
EnumConstantNotPresentException
enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on
IllegalMonitorStateException
an unlocked thread
Environment or application is in incorrect
IllegalStateException
state.
Requested operation not compatible with
IllegalThreadStateException
current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds
Exception Meaning
ClassNotFoundException Class not found
Attempt to clone an object that does not
CloneNotSupportedException
implement the Cloneable interface.
IllegalAccessException Access to a class is denied
Attempt to create an object of an abstract
InstantiationException
class or interface.
One thread has been interrupted by another
InterruptedException
thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
1) Throwable(Throwable cause):
The parameter cause specifies the actual cause of exception
2) Throwable(String str, Throwable cause):
The string str specifies exception description and cause specifies
the actual cause of exception.
Two methods of Throwable class that supports the chained exception.
1) ThrowablegtCause( ):
This method returns the actual cause of the currently
generated exception.
2) ThrowableinitCause( ):
This method sets the fundamental exception with invoking exception.
Example :-
The following java program shows that the program generates
ArithmeticException which in turn generates NumberFormatException.
class Demo
{
public static void main(String args[])
{
int n=10, result=0;
try
{
System.out.println(“The result is”+result);
}
catch(ArithmeticException ex)
{
System.out.println(“Arithmetic exception occoured:”+ex);
try
{
throw new NumberFormatException( );
}
catch(NumberFormatException ex1 )
{
System.out.println(“Chained exception thrown manually:”+ex1)
}
}
}}
Output-
Arithmetic exception occurred:
Java.lang.ArithmeticException:/ by zero
Chained exception thrown manually
Java.lang.NumberFormatException
The following example declares a new subclass of Exception and then uses that
subclass to signal an error condition in a method. It overrides the toString( )
method, allowing a carefully tailored description of the exception to be displayed.
1. Write a program to input name and age of a person and throws an user define
exception if entered age is negative.
import java.io.*;
classNegativeDemo
{
public static void main(String args[])
{
int age=0;
String name;
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter age and name of person");
try
{
age=Integer.parseInt(br.readLine());
name=br.readLine();
{
if(age<0)
throw new Negative("age is negative");
else
throw new Negative("age is positive");
}
}
catch(Negative n)
{
System.out.println(n);
}
catch(Exception e)
{
}
}}
import java.io.*;
2. Multithreaded Programming:-
First define a class that implements the Runnable interface. The Runnable interface
contains only one method, run(). The run() method is defined in method with the
code to be executed by the thread.
Threads are implemented in form of objects that contain a method called run(). The
run() method makes up entire body of thread and is the only method in which the
threads behaviour can be implemented.
Define a class that extends Thread class and override its run() method.
To create thread is to create new class that extends Thread and then to create
an instance of that class.
Extending the Thread class includes following steps
iii) Create a thread object and call the start() method to initiate the thread
execution.
Following statement create new thread
a) MyFirstThread t= new MyFirstThread();
Run instance of thread class or involve run()
b) T.start( );
Example for creating and extending the Thread class
Thread Life Cycle Thread has five different states throughout its life.
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Thread should be in any one state of above and it can be move from one state to
another by different methods and ways.
Topic 4. Exception Handling & Multithreaded Programming
1. Newborn state:
When a thread object is created it is said to be in a new born state. When
the thread is in a new born state it is not scheduled running from this state it can be
scheduled for running by start() or killed by stop(). If put in a queue it moves to
runnable state.
2. Runnable State:
It means that thread is ready for execution and is waiting for the availability of the
processor i.e. he thread has joined the queue and is waiting for execution. If all
threads have equal priority then they are given time slots for execution in round
robin fashion.
The thread that relinquishes control joins the queue at the end and again waits for
its turn. A thread can relinquish the control to another before its turn comes by
yield().
3. Running State:
It means that the processor has given its time to the thread for execution.
The thread runs until it relinquishes control on its own or it is pre-empted by a
higher priority thread.
4. Blocked state:
A thread can be temporarily suspended or blocked from entering into the runnable
and running state by using either of the following thread method.
Topic 4. Exception Handling & Multithreaded Programming
1) suspend() -
syntax : public void suspend()
This method puts a thread in suspended state and can be resumed using
resume() method.
2) resume()
syntax : public void resume()
This method resumes a thread which was suspended using suspend()
method.
3) yield()
syntax : public static void yield()
The yield() method causes the currently executing thread object to
temporarily pause and allow other threads to execute.
4) wait()
syntax : public final void wait()
This method causes the current thread to wait until another thread
invokes the notify() method or the notifyAll() method for this object.
The catch statement can take any one of the following four forms
1. catch(ThreadDeath e)
{
-------- //Killed thread
}
2. catch(InterruptedException e)
{
-------- //cannot handle it in current state
}
3. catch(IllegalArgumentException e)
{
---------- //Illegal method argument
}
4. catch(Exception e)
{
--------- // any other
}
Thread Priority:
Threads in java are sub programs of main application program and share the
same memory space. They are known as light weight threads. A java program
requires at least one thread called as main thread. The main thread is actually the main
method module which is designed to create and start other threads in java each thread
is assigned a priority which affects the order in which it is scheduled for
running. Thread priority is used to decide when to switch from one running thread to
another. Threads of same priority are given equal treatment by the java scheduler.
Thread priorities can take value from 1-10. Thread class defines default
priority constant values as
MIN_PRIORITY = 1
NORM_PRIORITY = 5 (Default Priority)
MAX_PRIORITY = 10
Thread Methods:
1. setPriority:
2. getPriority:
Syntax:public intgetPriority();
It obtain the priority of the thread and returns integer value.
Topic 4. Exception Handling & Multithreaded Programming
objC.setPriority(Thread.MAX_PRIORITY);
objB.setPriority(objA.getPriority() +1);
objA.setPriority(Thread.MIN_PRIORITY);
Topic 4. Exception Handling & Multithreaded Programming
}
}
2.8 Synchronization
Syntax-
synchronizedreturntypemethodname()
{
------ //code here is synchronized
}
2.10 Deadlock
1) Write a program to create two threads; one to print numbers in original order
and other to reverse order from 1 to 50. [W-14]
}
}
class reverse extends Thread
{
public void run()
{
for(intj=50; i >=1; i--)
{
System.out.println(" Second Thread="+i);
}
}
}
classorgrevDemo
{
public static void main(String args[])
{
System.out.println("first thread printing 1 to 50 in ascending order");
new original().start();
System.out.println("second thread printing 50 to 1 in reveres order");
new reverse().start();
System.out.println("Exit from Main");
}
}
2) Write a program to create two threads so one thread will print 1 to 10 numbers
whereas other will print 11 to 20 numbers.
Important Questions:-
1) Explain thread priority and method to get and set priority values.
2) Describe life cycle of thread.(4 times)
3) Describe use of „throws‟ with suitable example.
4) Explain following methods related to threads :1) suspend ( ) 2) resume (
)3)yield( ) 4) wait ( )
5) What is exception ? How it is handled ? Explain with suitable
example.(2 times)
6) Explain the following clause w.r.t. exception handling :(i) try(ii)
catch(iii)
throw(iv) finally
7) Write a program to input name and age of a person and throws an user define
exception if entered age is negative.
8) What is thread priority ? How thread priority are set and changed ? Explain
with example.(2 times)
9) Write a program to input name and age of person and throws user
defined exception, if entered age is negative .
10) Write a program to create two threads ; one to print numbers in original order
and other to reverse order from 1 to 50.
11) What are different types of error ? What is use of throw, throws and finally
statement?
12) Write a program to accept password from user and throw
„Authentication failure‟ exception if password is incorrect.