Java Unit-Iii
Java Unit-Iii
me/jntuh
UNIT – 3
The exception handling in java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.
What is exception
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown
at runtime.
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the
code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the
statement will be executed. That is why we use exception handling in java.
1
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
2
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked
exception. The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
1. try
2. catch
3. finally
4. throw
5. throws
Java try-catch
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
4
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Output:
As displayed in the above example, rest of the code is not executed (in such case, rest of the code...
statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be executed.
Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is
printed.
5
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a
default exception handler that performs the following tasks:
o Prints the stack trace (Hierarchy of methods where the exception occurred).
But if exception is handled by the application programmer, normal flow of the application is maintained
i.e. rest of the code is executed.
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
Rule: At a time only one Exception is occured and at a time only one catch block is executed.
Rule: All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception .
class TestMultipleCatchBlock1{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output:
Compile-time error
Syntax:
....
7
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
8
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Note: If you don't handle exception, before terminating the program, JVM executes finally block(if any).
9
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a
fatal error that causes the process to abort).
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is
mainly used to throw custom exception. We will see custom exceptions later.
1. throw exception;
Output:
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up before
the code being used.
o error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError
or StackOverflowError.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
12
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Output:
exception handled
normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or declare the
exception.
1. Case1:You caught the exception i.e. handle the exception using try/catch.
2. Case2:You declare the exception i.e. specifying throws with the method.
o In case you handle the exception, the code will be executed fine whether exception occurs during
the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
13
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
System.out.println("normal flow...");
}
}
Output:exception handled
normal flow...
o A)In case you declare the exception, if exception does not occur, the code will be executed fine.
o B)In case you declare the exception if exception occures, an exception will be thrown at runtime
because throws does not handle the exception.
System.out.println("normal flow...");
}
}
Output:device operation performed
normal flow...
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
14
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:Runtime Exception
1) Java throw keyword is used to explicitly Java throws keyword is used to declare an
throw an exception. exception.
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 e.g.
public void method()throws
IOException,SQLException.
By the help of custom exception, you can have your own exception and message.
17
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
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.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved by two ways:
o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)
o Each process have its own address in memory i.e. each process allocates separate memory area.
o Process is heavyweight.
o Switching from one process to another require some time for saving and loading registers, memory
maps, updating lists etc.
o Thread is lightweight.
18
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares
a common memory area.
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.
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
2. Runnable
3. Running
4. Non-Runnable (Blocked)
19
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start()
method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
20
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.Thread
class extends Object class and implements Runnable interface.
o Thread()
o Thread(String name)
o Thread(Runnable r)
2. public void start(): starts the execution of the thread.JVM 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.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
10. public Thread currentThread(): returns the reference of currently executing thread.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
21
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
19. public void setDaemon(boolean b): marks the thread as daemon or user 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.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following tasks:
o When the thread gets a chance to execute, its target run() method will run.
22
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
System.out.println("thread is running...");
}
If you are not extending the Thread class,your class object would not be treated as a thread object.So
you need to explicitely create Thread class object.We are passing the object of your class that
implements Runnable so that your class run() method may execute.
There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.
23
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
t1.start();
t2.start();
}
}
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the specified
time,the thread shedular picks up another thread and so on.
24
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
o Invoking the run() method from main thread, the run() method goes onto the current call stack
rather than at the beginning of a new call stack.
t1.run();
t2.run();
}
}
Output:1
2
3
25
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because here t1 and t2 will be
treated as normal object not thread object.
Syntax:
t2.start();
t3.start();
}
}
Output:1
26
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
2
3
4
5
1
1
2
2
3
3
4
4
5
5
As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.
t2.start();
t3.start();
}
}
Output:1
2
3
1
4
1
2
5
2
3
3
27
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
4
4
5
5
In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts
executing.
t1.start();
t2.start();
t1.setName("Sonoo Jaiswal");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Output:Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
The currentThread() method returns a reference to the currently executing thread object.
28
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Syntax:
t1.start();
t2.start();
}
}
Output:Thread-0
Thread-1
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
29
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides
information about the loaded classes, memory usage, running threads etc.
30
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
1) public void setDaemon(boolean is used to mark the current thread as daemon thread or
status) user thread.
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output
daemon thread work
user thread work
user thread work
31
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw
IllegalThreadStateException.
ThreadGroup in Java
Java provides a convenient way to group multiple threads in a single object. In such way, we can suspend,
resume or interrupt group of threads by a single method call.
2) ThreadGroup(ThreadGroup parent, String creates a thread group with given parent group
name) and name.
3) void destroy() destroys this thread group and all its sub groups.
32
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the class that
implements Runnable interface and "one", "two" and "three" are the thread names.
1. Thread.currentThread().getThreadGroup().interrupt();
ThreadGroup Example
File: ThreadGroupDemo.java
33
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
}
}
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
34
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be
done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization
Class Table{
}
}
}
35
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5
100
10
200
15
300
20
400
25
500
When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.
}catch(Exception e){System.out.println(e);}
}
}
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
37
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
500
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can
use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.
class Table{
38
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
39
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
class Table{
t1.start();
t2.start();
}
}
Output:5
10
15
20
25
100
200
300
40
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
400
500
Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on object.
class Table{
synchronized static void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
o wait()
o notify()
o notifyAll()
1) wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify() method
or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.
43
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
Method Description
public final void wait(long timeout)throws waits for the specified amount of
InterruptedException time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object,
one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the
lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
44
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
It is because they are related to lock and object has a lock.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
class Customer{
int amount=10000;
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
45
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh
www.android.universityupdates.in | www.universityupdates.in | https://telegram.me/jntuh
System.out.println("withdraw completed...");
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
46
www.android.previousquestionpapers.com | www.previousquestionpapers.com | https://telegram.me/jntuh