R.P.
Bhalodia BCA College
CH 3
Part-1
Exception Handling
1
Introduction to exception handling
During the execution of an application, there are many times when an error
condition arises within the application. In java, all kinds of error conditions are
called as exceptions. In other words we can say that In General; it is in the rare
case that our program will run successfully in its first attempt.
There are mainly two types of exceptions:
(1) Compile Time Exceptions (Syntax Errors)
All the syntax Errors are known as Compile Time Errors. These
types of errors are detected and displayed by the java compiler therefore
they are known as Compile Time Errors. This type of errors can be solved
before running the program so that after solving this type of errors we are
sure that our program is syntactically correct.
Remember that: Whenever the compiler will display the error it will
not generate the .class file.
Compile Time Errors Examples:
Missing Semicolons
Missing Brackets
Misspell of Keywords of Variables
Missing of double quotes in strings
Use of undeclared variables
Incompatible type conversion / assignment
use of = in place of ==
use of non initialized variable in keyboard reading
(2)Run Time Exceptions (Logical Errors)
Run time errors are those types of errors in which the program may
compiled successfully and the .class file also generated but when we run
that program it will produce the wrong result.
This will happened due to poor understanding of the logic or sometimes
due to misuse of the system resources.
Exception Handling:
The mechanism for Exception handling can be summarizing in the
following steps:
(1) Find the problem (Hit)
(2) Inform that an error has occurred (Throw)
(3) Receive the error information (Catch)
(4) Take the corrective Actions (Handle)
2
Java exception handling is managed via five keyword names are:
Try
Catch
Finally
Throw
Throws
1) Try: - program statements that you want to monitor for exception are
contains within a try block.
2) Catch: -if an exception occurs within the try block it is thrown. Your code
can catch this exception and handle it in come rational manner. System
generated exception hand by java run-time system.
3) Throw: - if want to throw manually at that time throw key word is used.
4) Throws: - any exception that is thrown out of a method must be specified
as such by throws clause.
5) Finally: - any code that must be executed after try block completes is put
in a finally block.
Format: -
try
{
//block of code to monitor for error
}
catch(Exception e)
{
//exception handler for error
}
catch(Exception e)
{
//exception handler for error
}
finally
{
//block of code must executed after try
}
3
Type of Exception: -
All types of exception are the subclass of the built-in class throwable.
Throwable is at the top of the exception class hierarchy.
Exception: -exception is the sub-class of the throwable. This class helps to
create your own custom exception type.
Error: -the exceptions that are not exception be caught under normal
circumstances by your program.
Here we are not going to discuss of the topic.
Uncaught Exception: -
Before we learn how to handle exception in your program, it is useful to see that
what happens when we don’t handle EXCEPTION.
class exe1
{
public static void main(String args[])
{
int d=0;
int a = 400/d;
System.out.println("The Anwer of A is : "+a);
}
}
Output:-
Exception in thread "main" java.lang.ArithmeticException: / by zero
at exe1.main(exe1.java:6)
4
Try, catch, finally and throws
Now exe1 is terminated automatically and display the run-time error.
How to solve this problem?
Answer is that to write try and catch block in the program.
try block contain the code which we want to monitor for exception.
catch block catch the exception that is generated in try block.
class exe2
{
public static void main(String args[])
{
int d=0;
try
{
int a = 400/d;
System.out.println("This will not be printed");
}
catch(Exception e)
{
System.out.println("Division by zero");
//System.out.println("The Exception is:"+e);
}
System.out.println("After catch statement");
}
}
In this program try block and catch block statement form a unit. In try block is
monitor for error. In the try contain any exception, the try block throw the
exception to the catch block. When program control to the catch that never goes
back to the try block.
Multiple Catch Clauses
In one program may contain more than one exception.
So, we handle this type of problem; write the more than two catch block.
Each catch block catching the different exception.
When exception is thrown, each catch statement is inspected (survey) in
order and the first one whose type matches that of the exception is
executed. After one catch statement executes, the other are bypass, and
execution continues after the try/catch block.
5
class MultipleCatch
{
public static void main(String arg[])
{
try
{
int arr[]={1,2,3};
arr[4]=6/0;
}
catch(Arithmetic Exception e)
{
System.out.println("Divide by Zero");
}
catch(ArrayIndexOutOfBoundException ex)
{
System.out.println("Array Index out of Bound Exception");
}
}
}
Nested try statement
The try statement can be nested. That is, a try statement can be inside the
block of another try.
Each time a try statement is entered, the context of that exception is
pushed on the stack.
If an inner try statement does not have a catch handler for a particular
exception, the stack is slow down and the next try statement’s catch
handlers are inspected for a match.
This continues until one of the catch statements succeeds, or until the
entire nested try statements are exhausted.
If no catch statement matches, then the java run-time system will handle
the exception.
//an example of nested try statements
class NestedTry
{
public static void main(String arg[])
{
try
{
int arr[]={10,20,30,40};
try
{
int x = arr[3]/arr[1];
6
}
catch(ArithmeticException e)
{
System.out.println("Divide by Zero");
}
arr[4]=3;
}
catch(ArrayIndexOutOfBoundException ex)
{
System.out.println("Array Index out of Bound");
}
}
}
throw
throw keyword use for manually throw the exception to the exception
handler.
Generally java run-time systems throw the exception implicitly.
Use of throw keyword to throw an exception explicitly, using the throw
statement.
Syntax :
throw <ThrowableInstance>;
here, throwable instance must be an object of type throwable or a subclass
of throwable.
There are two ways can obtain a throwable object.
o Using parameter into catch clause
o Creating one with the new operator.
Example of throw:
//DEONSTRATE THROW
class Throw_keyword
{
static void avg()
{
try
{
throw new ArithmeticException("throw Demo");
}
catch(ArithmeticException e)
{
System.out.println("Explict Exception");
}
}
7
public static void main(String arg[])
{
avg();
}
}
throws:
If a method is capable of causing an exception that it does not handle, it
may specify this behavior. So that callers of the method can guard them
solve again that exception.
You do this including a throws clause in the method’s declaration.
A throws clause lists the type of exception that a method might throw.
Example:
//this program contains an error and will not compile
import java.io.*;
class Demo
{
public static void main(String arg[])throws IOException
{
char g;
g=(char)System.in.read();
if(g=='F'||g=='f')
System.out.println("Female");
else
System.out.println("Male");
}
}
8
finally
The finally block always run if exception is generated or not.
This block helps to close the file, free resources when we use in method.
The finally block is optional.
Operations are..
1) Closing a file
2) Closing a record set
3) Closing the connection with database.
4) Terminating Network Connection.
//Demonstrate finally
class Finally_Block
{
public static void main(String arg[])
{
try
{
int a=5;
int b=0;
int c=a/b;
System.out.println("division="+c);
}
catch(ArithmeticException e)
{
System.out.println("This will be always Executed");
}
finally
{
System.out.println("Finally Block");
}
}
}
OutPut:-
9
Creating user defined exception class
Java provides built-in Exception to handle most common errors. Then also
java provides user to create exception,which are called custom exception
or user defined exception. User can create their own exception classes
so application-specific problems can be handled.This can be done simply by
extending java Exception class.
class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
{
throw new InvalidAgeException("not eligible for vote");
}
else
{
System.out.println("welcome to vote");
}
}
}
class CustomException
{
public static void main(String args[])
{
int age = Integer.parseInt(args[0]);
try
{
TestException1.validate(age);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
10
Multithreading
Thread and its life cycle (thread states)
Introduction:
Multithreading in java is a process of executing multiple threads
simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of
processing. Multiprocessing and multithreading, both are used to achieve
multitasking.
But we use multithreading than multiprocessing because threads share a
common memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than
process.
Java Multithreading is mostly used in games, animation etc.
Advantages of Java Multithreading:
1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in
a single thread.
What is Thread in java?
A thread is a lightweight sub process, a smallest unit of processing. It is a
separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't
affect other threads. It shares a common memory area.
11
As shown in the above figure, thread is executed inside the process. There
is context-switching between the threads. There can be multiple processes
inside the OS and one process can have multiple threads.
Thread Life Cycle:
A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in java new, runnable, non-runnable and terminated. There is
no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states
are as follows:
1. New Thread
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
12
When we create any thread object, it is said to be in newborn state.
At this stage we can do two things (1) start (2) stop.
The Runnable state means that the thread is ready for execution and
is waiting for availability of the processor. The thread is in queue now and
waiting for execution. Generally they will be executed in FCFS(First
Come First Serve) manner.
In Running state means the processor has given its time to thread for
its execution. The thread runs till it gives control to another.
There is one method called suspend() which can be again put in
running by resume() method.
13
We can make a thread to sleep. We can put a thread to sleep by using
sleep(time) where time is in miliseconds. The thread will re-enter into the
runnable state as soon as the time is over.
It has been told to wait until some event occurs. This is done using wait()
method. The thread can be scheduled to run again using notify() method.
Example:-
class Thread_life
{
public static void main(String arg[])
{
Thread.State states[] = Thread.State.values();
for(Thread.State s:states)
System.out.println(s);
}
}
Output:-
New
Runnable
Blocked
Waiting
Timed_Waiting
Terminated
14
Thread class and its methods
Java multithreading system is built upon the Thread class, its methods,
and its companion interface, Runnable.
To create a new thread, your program will either extend Thread or
implement the Runnable interface.
The thread class defines several methods that help manage threads. The
ones that will be used in this chapter are shown here:
Method Description
void destroy() To destroy the Thread from the memory
String getName() Returns the name of the thread.
int getPriority() Returns the priority of the thread.
void interrupt() Interrupts the current thread.
boolean interrupted() Tests whether the thread is interrupted or not
boolean isAlive() Tests whether the thread is alive or not
void join() Wait for the calling thread to die.
void join(long millis) Wait atmost <millis> millisecond for this thread to die.
void resume() Resumes the thread execution
void setPriority(int Change the priority of the thread
newPriority)
void sleep(long Causes the currently executing thread to sleep
millis) (temporarily cease execution) for the specified number of
milliseconds.
void start() Causes this thread to begin execution; the Java Virtual
Machine calls the run method of this thread.
void stop() Stops the execution of current thread
void suspend() Suspends the current thread execution until the resume
method has been called.
void yield() Causes the currently executing thread object to
temporarily pause and allow other threads to execute.
15
Creation of New Thread:
Java provides two ways to create a new thread.
By Extending the Thread class which is available in package
java.lang.Thread
Example:
class myThread extends Thread
{
……..
……..
}
//Write a program to create thread in java
class Thread1 extends Thread
{
public void run()
{
for(int i=0;i<100;i++)
System.out.println("Thread1:="+i);
}
}
public class Thread_Demo
{
public static void main(String arg[])
{
Thread1 t1 = new Thread1();
t1.start();
for(int i=0;i<100;i++)
System.out.println("Main:="+i);
}
}
Output:- Output cannot be predicted Exactly…
Thread Priority:
In Java each thread will be assigned a priority, which affects the order of
its execution.
If the two or more threads have same priority then they have been given
equal treatment by Java scheduler and they will be processed on FCFS
basis.
On the other hand we – the programmers can also set the priority by using
setPriority() method.
In setPriority() method we have to pass integer no. or constant according to
our requirement just like
threadname.setPriority(intnumber)
16
Thread class has sevelral constants also they are
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Remember that the default setting is NORM_PRIORITY
When java program gets a new thread with higher priority than presently
running thread then the presently running thread will move into the
runnable state and new thread will come in to execution.
//demo of priority method min,norm,max using thread class
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("From Thread A : i = "+i);
}
System.out.println("Exit From Thread A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("From Thread B : j = "+j);
}
System.out.println("Exit From Thread B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("From Thread C : k = "+k);
}
System.out.println("Exit From Thread C");
}
}
17
class ThreadDemo2
{
public static void main(String args[])
{
A thread_a=new A();
B thread_b=new B();
C thread_c=new C();
System.out.println("Thread A Started");
thread_a.setPriority(Thread.MAX_PRIORITY);
thread_a.start();
System.out.println("Thread B Started");
thread_b.setPriority(Thread.NORM_PRIORITY);
thread_b.start();
System.out.println("Thread C Started");
thread_c.setPriority(Thread.MIN_PRIORITY);
thread_c.start();
}
}
Runnable Interface:
From the first we know that threads can be created in two ways:
(1) By extending Thread class
(2) By implementing Runnable Interface.
Runnable Interface will work same as extending thread class. But it is
useful when we need to extend some other class at that time this implementation
will be much useful.
class Thread1 implements Runnable
{
public void run()
{
for(int i=0;i<100;i++)
System.out.println("Thread1:="+i);
}
}
public class Runnable_Demo{
public static void main(String arg[]){
Thread1 t1 = new Thread1();
Thread t2 = new Thread(t1);
t2.start();
for(int i=0;i<100;i++)
System.out.println("Main:="+i);
}
}
18
Synchronization in multiple threads (Multithreading)
In java, the threads are executed independently to each other.These types
of threads are called as Asynchronous threads.While working with
multiple threads,it may be possible that more than one threads share the
same data at a time.For example one thread might try to read the data when
other thread tries change it.This might generate error in result.In this
case,it is necessary to allow one thread to finish its task completely and
then allow next thread to execute.This can be done with the help of
synchronized() Method.
An example consider a bank account that shared by multiple customers.
Each of the customer can make deposited or withdrawal in his account.
Consider a situation in which you have developed individual thread for
individual customers.
If we have thread a or customer A. now customer A want to deposit Rs
10000 in his account and the present balance is zero.
At the same time customer B also deposit Rs 1000 in his bank account. So
that he also gets the balance 0(zero).
This solution to the above problem is to access the common data. For this
purpose java has given us a special keyword called synchronized which
makes a lock on the method which is executes. So that the second thread
will not get control of CPU until the first thread over.
class Demo
{
synchronized void test()
{
for(int i=1;i<100;i++)
System.out.println("Demo:"+i);
}
}
class Thread2 extends Thread
{
Demo d;
Thread2(Demo d)
{
this.d=d;
}
public void run()
{
d.test();
}
}
19
class Thread3 extends Thread
{
Demo d;
Thread3(Demo d)
{
this.d=d;
}
public void run()
{
d.test();
}
}
class Syn_example
{
public static void main(String arg[])
{
Demo d = new Demo();
Thread2 t2 = new Thread2(d);
Thread3 t3 = new Thread3(d);
t2.start();
t3.start();
}
}
Deadlock:-
When two thread have circular dependency on objects a major
problem arise.
This type of error is known as “deadlock”
In deadlock, one thread is waiting for other thread & the other
thread is waiting for the first thread.
Thus, both threads go in waiting (blocked) state & can not
continue their execution
Each class has a synchronized method & both by creating two
different thread objects.
20
Each class has a synchronized method & both classes.
Objects access the synchronized method.
The result of deadlock is a blocked condition.
You have to press ctrl + c to come out from this blocked
situation.
//example of deadlock
class A
{
synchronized void test1()
{
System.out.println("Start Test");
try
{
wait();
}
catch(InterruptedException ex)
{
System.out.println(ex);
}
System.out.println("End");
}
synchronized void release()
{
notify();
}
synchronized void releaseAll()
{
notifyAll();
}
}
class Thread1 extends Thread
{
A a1;
Thread1(A a1)
{
this.a1=a1;
}
public void run()
{
a1.test1();
21
}
}
class Thread2 extends Thread
{
A a1;
Thread2(A a1)
{
this.a1=a1;
}
public void run()
{
a1.test1();
}
}
class DeadLoack
{
public static void main(String arg[])
{
A a1 = new A();
A a2 = new A();
Thread1 t1 = new Thread1(a2);
Thread1 t2 = new Thread1(a2);
t1.start();
t2.start();
try
{
Thread.sleep(10000);
}
catch(InterruptedException ex)
{
System.out.println(ex);
}
System.out.println("Releasing");
a1.releaseAll(); //a2.releaseAll();
}
}
Output:-
DeadLoack Releasing Deadloack Condition
Start Test Start Test
Start Test Start Test
Releasing Releasing
End(execution will not got over) End
End
22
Daemon thread, Non-Daemon Thread
In Java, any thread can be a Daemon thread. Daemon threads are like a service
providers for other threads or objects running in the same process as the daemon
thread. Daemon threads are used for background supporting tasks and are only
needed while normal threads are executing.
If normal threads are not running and
remaining threads are daemon threads then the interpreter exits.
Daemons are used for background tasks that make sense only when there are
other threads that are doing the real work. The garbage collector is an excellent
example of a proper use of daemons. You can set the daemon flag on or off as
your program requires with thread.setDaemon(), but you can only do this
before you call start(). You cannot change the status of a running thread.
You can also check the status of a thread with isDaemon(). You will probably
never use daemons.
There are two methods of thread for daemon
(1) void setDaemon (Boolean daemon)
(2) boolean isDaemon()
class DaemonThread extends Thread
{
public void run()
{
System.out.println("Entering run method");
try
{
System.out.println("In run Method: currentThread() is" +
Thread.currentThread());
while (true)
{
try
{
Thread.sleep(500);
}
catch (InterruptedException x)
{
}
System.out.println("In run method: woke up again");
}
}
catch(Exception e)
{
}
finally
{
23
System.out.println("Leaving run Method");
}
}
public static void main(String[] args)
{
System.out.println("Entering main Method");
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
try
{
Thread.sleep(3000);
}
catch (InterruptedException x)
{
}
System.out.println("Leaving main method");
}
}
24