You are on page 1of 13

Unit-IV Exception Handling

Types of Errors:

1.Compile-Time Error
2.Run-Time Error
1.Compile Time Error: All Syntax errors will be detected and displayed by the java
compiler and therefore these errors are known as compile time errors. Whenever the
compiler displays an error, it will not create the .class file.
Eg:
• Missing Semicolons
• Mismatch of brackets in the class and methods
• Misspelling the identifiers and keywords
• Use of undeclared variables
2.Run-Time Error:
A Program may compile successfully creating the .class file but
may not run properly. Such programs may produce wrong result due to wrong logic
or may terminate due to errors
Eg:
• Dividing an integer by zero
• Accessing an element that is out of bounds of an array
• Converting invalid string to a number
• Passing parameter that is not in a valid range
Exceptions
• An exception is an abnormal condition that is caused by a run-time error in the
program.
• The way of handling the various types of exceptions that occurs during the
execution of the program is known as exception handling.
• Some of the error classes are described below:

Srimad Andavan Arts and Science College


Department of Computer Sciecne
Name of the class Description of the Error-Condition
ClassNotFoundException A Class is not found
Run-timeException A run-time error condition has
Occurred
ArrayIndexOutOfBoundsException A non-exist array position is
accessed through a wrong index
ArithmeticException An arithmetic error ,such as divide-
by-error has occurred
IOException An input/output related error has
Occurred
NumberFormatException A wrong conversion is made
between a string and a numeric
Value

Syntax

Exception Object Creator

Throws Exception

Exception Handler
Object

Eg:
try
{
statement; //generates exception
}

catch(Exception-type e)
{
Srimad Andavan Arts and Science College
Department of Computer Sciecne
statement; //process the exception
}

Srimad Andavan Arts and Science College


Department of Computer Sciecne
▪ The try block can have one or more statements that could generate an
exception.
▪ If any one generates an exception the remaining statements in the block
are skipped.
▪ The catch block can have one or more statements that are necessary to
process the exception.
▪ The try statement should be followed by atleast one catch statement.

Multiple Catch Statement:


• More than one catch statement is possible to implement.
Syntax:
try
{
statement; //generates exception
}

catch(Exception-type-1 e)
{
statement; //process the exception type-1
}
catch(Exception-type-2 e)
{
statement; //process the exception type-2
}
catch(Exception-type-3 e)
{
statement; //process the exception type-3
}
…..
……
catch(Exception-type-N e)
{
statement; //process the exception type-N
}

• When an exception in a try block is generated, the java compiler treats the multiple
catch statements like cases in switch statement.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
• The first statement whose parameter matches with the exception object will be executed
and the remaining will skipped.

Nested Try:
1. The try statement can be nested. A try statement inside the block of another try
is called nested try.
2. If an inner try statement does not have a catch handler for a particular exception,
then it is unknowned exception and the next try statement’s catch handler are
matched.
3. If no catch statements matches, then the java run-time system will handle the
exception.
Syntax:
try
{
……
……….
try
{
………
………..
}
catch(…..)
{
………
………….
}
}
catch(………)
{
………..
…………..
}

Finally Statement
➢ Java supports another statement known as finally statement that can be used to
handle an exception that is not caught by any of the previous catch statements.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
Syntax:

try try
{ {
…… ……
……… ………
} }
finally Or catch()
{ {
……… ………
………… …………
} }
finally
{
………
…………
}
• When a finally block is defined, this will execute whether or not in exception
thrown.
Throw
• throw keyword is used to throw our own Exception.
Syntax:
throw new Throwable_subclass;
• Here throwable_subclass must be an object of type Throwable or a subclass
of Throwable.
• There are two ways of obtaining a Throwable object,
1. Using a parameter into a catch clause or
2. Creating one with the new operator.
• The flow of execution stops immediately after the throw statement.
Throws:
• If a method is capable of causing an exception that it does not handle, it must
specify the behavior of guard the exception. A throws clause is used to handle
this.
• A throws clause lists the type of exceptions that a method might throw.
• The exceptions that a method can throw must be declared in the throws clause.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
• If the method does not declare, then compile time error will be occurred.
Syntax:
type method-name(parameter-list)throws exception-list
{
//body of method
}

Multithreading
Thread
A thread is a program unit that is executed independently of other parts of the
program.
Life Cycle of a Thread
Every thread moves through several states from its creation to its
termination. The possible states of a thread are, New, Ready(Runnable), Running, Waiting
and Dead

New State

Running
Dead

Wait

The Thread will be in the new state after the creation of the thread. After the start()
method of the thread is executed, it will move to the ready state. When the JVM selects it for
execution, it will move to the running state. When the thread completes its execution ,it will
move to the dead state.
Srimad Andavan Arts and Science College
Department of Computer Sciecne
If a thread is instructed to wait, it moves to the waiting state. when the waiting is over
,the thread once again moves to the ready state. Sometimes,the JVM may move a thread from
the running state to the ready state in order to offer another thread to execute.

NewBorn State
When we create thread object, the thread is born and is said to be in
newborn state. At this state we can perform the following two methods start() and stop().

Runnable State
The runnable state means that the thread is ready for execution and
is waiting for the availability of the processor. if all threads that are waiting for execution has
equal priority, then they are given time slots for execution. The yield() method is used to
relinquish the control to other method.

Running State
The Running state means that the processor has given its time to the
thread for its execution. the running thread may block its control by the following
methods,
1. It has been suspended by suspend() method. Then it can be revived by using the
resume() method.
2. It has been made to sleep by using sleep(time) method.
3. It has been said to wait until some event occurs by wait() method and the thread
can be run again using notify() method.

Blocked State
A thread is said to be blocked when it is prevented from entering into
the runnable state and the running state. This happens when a thread is suspended, wait or
sleeping state.

Dead State
A running thread ends its life when it has completed its run() method.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
Creating and Running Threads
▪ We shall create and run a thread by using the Thread class, which is
available in java.lang package. Each thread is either an instance of this
class or the instance of a subclass of this class.
▪ We can also create a thread by using the Runnable interface. This
interface contains the declaration of only one method, namely run().

Example: Program to create thread using Thread class

class demothread extends Thread


{
public void run()
{
try
{
for(int i=1;i<=3;i++)
{
Thread.sleep(1000);
System.out.println(“Welcome”);
}
}
catch(InterruptedExceptrion e){}
}
}
class demo
{
public static void main(String args[])
{
demothread d=new demothread();
d.start();
}
}
Output: Welcome
Welcome
Welcome

Program to create thread using Runnable Interface

class demo implements Runnable


{
public void run()
{
try
{
Srimad Andavan Arts and Science College
Department of Computer Sciecne
for(int i=1;i<=3;i++)
{
Thread.sleep(1000);
System.out.println(“Welcome”);
}
}
catch(Exceptrion e){}
}
}
class demomain
{
public static void main(String args[])
{
demo d=new demo();
Thread t=new Thread(d);
t.start();
}
}
Output: Welcome
Welcome
Welcome

Methods in the Thread Class:


The thread can be construct by the methods as follows:
❖ Thread t=new Thread()
❖ Thread t=new Thread(Runnable r)
❖ Thread t=new Thread(String s)
❖ Thread t=new Thread(Runnable r,String s)
Apart from this constructor method, there are static methods and instance
methods in Thread Class.
Static Method:
Syntax Purpose

static Thread currentThread To return a reference to the current


thread
static void sleep(long m) To cause the current thread to wait for
m milliseconds
static void sleep(long m,int n) To cause the current thread to wait for
m milliseconds plus n nanoseconds
Srimad Andavan Arts and Science College
Department of Computer Sciecne
Instance Method:
Syntax Purpose

void start() To start the specific thread.


void run() This method encapsulates the functionality
of a thread. This method is always
boolean isAlive() overridden.
To return the value true if a thread has
been started and has not yet died.
void setName(String s) Otherwise it returns false.
String getName() To set the name of the specified thread to
void setPriority(int p) s.
int getPriority() To return the name of the specified
thread.
To set the priority of the specified thread
to p.
To return the priority of the specified
thread.

o We can place two or more threads in a program into a ThreadGroup


o We have to create an object for the ThreadGroup class
ThreadGroup g=new ThreadGroup(“FirstGroup”);
1. We have to associate the object g with an object of the Thread class as shown
below
Thread t=new Thread(g,runnable);
2. Here, runnable is an object of a class that implements Runnable interface
3. All the Threads associated in the thread group can be get started through the
following command
g.start();
Where the object g is the object of ThreadGroup.
Setting the Priority Of a Thread
Srimad Andavan Arts and Science College
Department of Computer Sciecne
We can assign different priorities to the threads by using the setPriority()
method.
O The priority parameters always take a value between 0 and 10.
O The priority of the thread is set by one of the following static constants.
1. MAX_PRIORITY
2. MIN_PRIORITY
3. NORM_PRIORITY
1. Where MAX_PRIORITY represents 10 points on a relative scale.
2. Where MIN_PRIORITY represents just 1 point on a relative scale.
3. Where NORM_PRIORITY represents 5 points on a relative scale, which is
the default priority level
➢ Whenever the thread scheduler needs to take a decision regarding which thread to
run next, it picks the thread with highest priority.
➢ If there are many threads with the same high priority in the queue, the scheduler
chooses one of the highest priorities.
Synchronization
• Since all the threads in a program share the same memory space, two or more threads in
a program may try to access the same method. Data corruption may occur if the access
to method by many threads is not properly regulated
• The access to a method shall be synchronized by specifying the synchronized keyword
as a modifier in the method declaration.
DeadLock
o When two or more threads are used in a program, an unusual condition namely the
Deadlock condition sometimes occurs.
o This condition occurs when two or more threads wait indefinitely for each other to
hold locks
Inter-Thread Communication:
▪ We can make the threads communicating among themselves with the help of the
interthread communication.
▪ The wait(), notify() and notifyAll() methods are used to establish the inter-thread
communication.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
▪ When the wait() method is invoked inside a synchronized method, the object lock
that is held by the current thread is temporarily released. In addition the current
thread is deactivated.

Srimad Andavan Arts and Science College


Department of Computer Sciecne

You might also like