1
Module 3
EXCEPTION HANDLING
Exception is a condition that is occurred by a run time in a program. That is an
exception is an event, which occurs during the execution of the program, that an interrupt the
normal flow of the program’s instruction
When java interpreter encounters an error such as division by zero, it creates an
exception object and throws it. If the exception object is not caught and handled properly the
interpreter will display an error message and terminates the program.
If we want to continue the execution of the remaining code, then we should catch the
exception object thrown by error condition and display an error message to correct it. This
task is known as exception handling.
Exceptions are mainly of two types
Checked Exception
Unchecked Exception
Checked Exception
A checked exception is an exception that occurs at compile time , these are also called as
compile time exceptions. These exceptions cannot simply be ignored at the time of
compilation, the programmer should take care of these exceptions.
Eg:- if you use FileReader class in your program to read the data from a file, if the file
specified doesn’t exist then an FileNotFoundException occurs and the compiler prompts the
programmer to handle the exception.
Unchecked Exception
An unchecked exception is an exception that occurs at the time of execution, these are
also called as Runtime exceptions. These include programming bugs such as logic errors etc.
runtime exceptions are ignored at the time of compilation.
Eg:- if you have declared an array of size 5 in your program, and trying to call the 6 th element
of the array then an ArrayindexOutOfBoundsExceptions occurs.
Errors
These are not exceptions at all, but problems that arise beyond the control of the user of the
programmer. Errors indicate serious problems and abnormal conditions that most applications
should not handle. Error defines problems that are not expected to be caught under normal
circumstances by our program.
Eg:- memory error, hardware error etc.
Common exceptions are
ArithmeticException
ArrayIndexOutOfboundsException
ArrayStoreException
2
FilenotFoundException
IOException
NullPointerException
NumberFormatException
stackOverflowException
Exception Handling in Java
In java exception handling is done using five keywords.
Try
Catch
Throw
Throws
Finally
Using Try and catch
Try is used to guard a block of code in which exception may occur. A try/ catch block is
placed around the code that might generate an exception. Code within a try/catch block is
referred to as protected code.
The block of code that is likely to cause an error condition is placed in ‘try’ and it throws an
exception a ‘catch’ block is defined immediately after a try block catches the exception.
Syntax
try
{
-----
}
catch()
{
------
}
There is usually at least one catch block immediately after the try block
a catch block must specify what type of exception it will catch.
--In the try block if an error occurs the remaining faults are skipped and execution jumps to
the catch block that is placed next to the try block.
--One try block should have atleast one catch block.
-- there
can be more than one catch block, each one marked for a correct exception class
--Any catch block that matches the exception is executed and others are skipped. If no match
is found then default exception handler will cause the execution to terminate.
--It is possible to define any number of catch block
3
public class demo
{
public static void main(String[] args)
{
int ans1, ans2;
int a = 2, b = 2, c = 0;
try
{
ans1 = a/b;
[Link]("a/b = " + ans1);
ans2 = a/c;
[Link]("a/c = " + ans2);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception!");
}
[Link]("demo is over");
}
}
Output:
a/b = 1
Arithmetic Exception!
demo is over
Using Multiple catch Blocks
It is possible that a statement might throw more than one kind of exception. We can
list a sequence of catch blocks, one for each possible exception.
class error
{
Public static void main(String args[])
{
int a=10, b=5,c=5;
int []x={1,2,3},y;
try
{
y=a/(b-c);
[Link](a[3]);
}
catch(Arithmeticexception e)
{ [Link](“division by zero”); }
catch(ArrayIndexOutOfBoundsException e)
{ [Link](“array index not accessible”); }
int z=a+b;
[Link](z);
}
4
}
Nested try statement
‘try’ statements can be nested ie, the try statement can be inside the block of another try. If
the try statement doesn’t have a catch handler for a particular exception, the stack is unwound
and the next try statement’s catch handlers are inspected for a match. This continues until a
match catch is found or until all of the nested try statements are exhausted.
Syntax
try
{
try
{
-------
}
catch
{
- - - - - --
}
}
catch
{
- - - - - -- -
}
If no match is found java run time system will handle the exception.
class nestedtry
{
public static void main(String as[])
{
try
{
int a=0;
int b=40/a;
[Link](b);
try
{
If(a==1)
b=a/(a-1);
}
catch(ArrayIndexOutOfBoundsException e)
{ [Link](“array index not accessible”); }
}
catch(Arithmeticexception e)
{ [Link](“division by zero”); }
5
}
}
Throw
1. The throw statement causes termination of the normal flow of control of the java code and
prevents the execution of the subsequent statements.
2. The throw clause convey the control to the nearest catch block handling the type of
exception object throws.
3. If no such catch block exists, the program terminates.
‘throw’ keyword is used to throw an exception explicitly. The general form of throw is shown
below:
throw throwableinstance;
only object of throwable or its subclass can be thrown. The flow of execution stops
immediately after the throw statement. The nearest enclosing ‘try’ block is inspected to see if
it has a catch statement that matches the type of the exception. If no matching catch is found
then the default exception handler halts the program.
In java, a user can create user defined exceptions. For this ‘throw’ keyword is used. You can
also throw already defined exception.
public class testthrow
{
static void validate(int age)
{
if (age<18)
throw new ArithmeticException(“not valid”);
else
[Link](“Welcome to vote”);
}
public static void main(stirng as[])
{
validate(13);
[Link](“Rest of code”);
}
}
Throws
A throws clause lists the types of exceptions that a method might throw. Any method
capable of causing exceptions must list all the exceptions possible during its execution, so
that anyone calling that method gets a prior knowledge about which exceptions to handle. A
methos can do so by using ‘throws’ keyword.
Syntax
6
type method_name(parameters list) throws exceptionlist
{
//body of method
}
Here, exception list is a comma separated list of the exception that a method can
throw.
class Demo
{
static void throwMethod() throws NullPointerException
{
[Link](“inside throw”);
throw new Nullpointerexception(“demo”);
}
public static void main(String as[])
{
try
{
throwMethod();
}
catch(NullPointerException e)
{
[Link](“the exception get caught”+exp);
}
}
}
Difference between throw and throws
No. throw Throws
1 Java throw keyword is used explicitly to Throws keyword is used to declare an
throw an exception exception
2 Checked exception cannot be propagated Checked exception can be propagated
using throw with throws.
3 Throw is followed by an instance Throws is followed by class
4 Throw is used within the method. Throws is used with the method signature.
5 You cannot throw multiple exceptions You can declare multiple exceptions
Finally
7
Java supports another statement known as finally that can be used to handle an
exception that is not caught by any of the previous catch statement.
--The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an exception.
--A finally block appears at the end of the catch blocks and has the following syntax
try
{
- - - - - - - --
}
catch()
{
- - - - -- - -
}
finally
{
- -- -----
}
‘ Finally’ block is guaranteed to execute regardless of whether or not an exception is thrown.
It is usually used to closing files and releasing system resources.
a try block is followed by zero or more catch blocks
There may one finally block as the last block in the structure.
There must be at least one block from the collective set of catch and finally after the
try.
It's possible to have a try block followed by a finally block, with no catch block.
public class demo
{
public static void main(String args[])
{
try
{
[Link]("Try Block before the error.");
[Link](1/0);
[Link]("Try Block after the error.");
}
catch(ArithmeticException e)
{
[Link]("Catch Block");
[Link]("The operation is not possible.");
}
finally
{
[Link]("Finally Block");
8
}
[Link]("demo is over");
}
}
Output:
Try Block before the error.
Catch Block
The operation is not possible.
Finally Block
demo is over
Generating User Defined Exception
In java we can create our own exception class and throw that exception using throw
keyword. These exceptions are known as user-defined or custom exceptions
Example of User defined exception in Java
// A Class that represents use-defined expception
class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
// A Class that uses above MyException
public class Main
{
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException("Hai");
}
catch (MyException ex)
{
[Link]("Caught");
// Print the message from MyException object
[Link]([Link]());
}
}
}
Output:
Caught
Hai
MULTITHREADED PROGRAMMING
9
Multithreading is a conceptual programming paradigm where a program is divided
into two or more subprograms(processes) which can be implemented at the same time
in parallel. Thus multithreading is a process of executing multiple threads
simultaneously.
A multithreaded program contains two or more parts that can run concurrently. Each
part of such a program is called a thread. Threads are light-weight.
A thread is similar to a program that has a single flow of control. It has a beginning, a
body and an end and executes commands sequentially.
A program have multiple flows of control is known as multithreaded program.
Ability of a language to support multithreading is known as concurrency.
Multithreading make maximum use of the CPU.
Advantages
a) It doesn’t block the user because threads are independent and can perform multiple
operations at the same time.
b) One can perform many operations together so it saves time.
c) Threads are independent so it doesn’t affect other threads if exception occur in a
single thread.
Creating threads
There are two ways to create a thread in java:
By extending Thread class
By implementing Runnable interface
Some of the methods in thread class include
getName():- is used for obtaining a thread’s name.
getPriority():- obtain a thread’s priority.
isAlive():- determine if a thread is still running.
join():- wait for a thread to terminate.
run():- entry point for the thread
sleep():-suspend a thread for a period of time.
start():- start a thread by running its run() method.
Method 1: Thread creation by extending thread class
The first method to create a thread is to create a new class that extends Thread class
using the following two simple steps. This approach provides more flexibility in handling
multiple threads created using available methods in Thread class.
Step 1:-
10
To override run() method available in Thread class. This method provides entry point
for the thread and one can put the complete business logic inside this method. Following is
the simple syntax for run() method.
public void run();
Step 2:-
Once Thread object is created, we can start it by calling start() method, which
executes a call to run() method . Following is the simple syntax for start() method.
void start();
Example
import [Link].*;
class A extends Thread
{
public void run()
{
for (int i=1;i<=5;i++)
{
[Link](“\n In class A:”+i);
}
[Link](“exit from A”);
}
}
class B extends Thread
{
public void run()
{
for (int j=6;j<=10;j++)
{
[Link](“\n In class B:”+j);
}
[Link](“exit from B”);
}
}
class C extends Thread
{
public void run()
{
for (int k=11;k<=15;k++)
{
[Link](“\n In class C:”+k);
11
}
[Link](“exit from C”);
}
}
class threadabc
{
public static void main(String as[])
{
A a = new A();
B b = new B();
C c = new C();
[Link]();
[Link]();
[Link]();
}
}
Method 2: Create thread by implementing Runnable interface
If a class is intended to be executed as a thread, this can be achieved by implementing
Runnable interface.
Step 1:-
As a first step we need to implement a run() method provided by Runnable interface.
This method provides entry point for the thread and we can put complete business logic
inside this method. Following is the syntax for run() method.
Public void run();
Step 2:-
At second step we can instantiate a Thread object using the constructor.
Thread(Runnable threadobj, String threadname);
Where, threadobj is an instance of a class that implements the runnableInterface and
threadName is the name given to the new thread..
Step 3:-
Once thread object is created , we can start it by calling start() method, which
executes a call to run() method. Following is a simple syntax of start() method.
void start();
Example:-
12
class A implements runnable
{
public void run()
{
int I;
for(i=1; i<5; i++)
{
[Link](“Thread:” +i);
}
[Link](“End of thread”);
}
}
class AB
{
public static void main(String as[])
{
A a = new A();
Thread t = new Thread(a);
[Link]();
[Link](“End of main”);
}
}
Life cycle of a thread
A thread exists in several states.
New born
Runnable
Running
Blocked
Dead
new thread
New born
stop
start
Killed thread
dead
Active stop
thread
suspend stop
13
sleep resume
wait notify
blocked
Idle thread
1) New born state:-
A thread begins its life cycle in the new state. It remains in its state until the program
starts the thread. It is also referred to as born thread.
For creating a thread object one of the following can be done
a) Schedule it for running state using start().
b) Kill it using stop().
2) Runnable state:-
After a newly born thread is started, the thread becomes runnable. Thread is ready for
execution and is waiting for the availability of the process.
Transfer is controlled to another thread of equal priority.
3) Running state:-
The thread can be ready to run as soon as it gets CPU time. A running thread can be
suspended , which temporarily suspends its activity. A suspended thread can be resumed.
a) Suspend() and resume()
public void suspend() :- this method puts a thread in suspended state and can be resumed
using resume() method.
14
public void resume(): - this method resumes a thread which was suspended using suspend()
method.
b) sleep(time)
The sleep() method cause the currently executing thread to sleep for the
specified number of milliseconds.
c) wait() and notify()
public void wait():- causes the current thread towait until another thread invokes the notify().
public void notify(): - wakes up a single thread that is waitimg on this object’s monitor.
4) Blocked
A thread is waiting for another thread to perform a task. In this stage the thread is still
alive.
5) Dead state
A runnable thread enters the terminated state when it completes its task or otherwise
terminates.
15
Example
import [Link].*;
class A extends Thread
{
public void run()
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
yield();
[Link](“\n thread A:”+i);
}
[Link](“\n Exit from A”);
}
}
class B extends Thread
{
public void run()
{
int j;
for(j=1;j<=5;j++)
{
if(j==3)
stop();
[Link](“\n thread B:”+j);
}
[Link](“\n Exit from B”);
}
}
class C extends Thread
{
public void run()
{
int k;
for(k=1;k<=5;k++)
{
[Link](“\n thread C:”+k);
if(k==1)
{
try
{
sleep(1000);
}
catch(Exception e)
16
{ [Link](e); }
}
[Link](“\n Exit from A”);
}
}
Thread class:
Thread class provide constructors and methods to create and perform operations on a [Link]
class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r, String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public [Link] getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
17
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.