Java Unit-3
Java Unit-3
Exception Handling
Exception-Handling Fundamentals
That method may choose to handle the exception itself, or pass it on.
If an exception occurs within the try block, it is thrown. Your code can
catch this
exception (using catch) and handle it in some rational manner.
Any code that absolutely must be executed after a try block completes is
put in a finally block.
Exception Types
All exception types are subclasses of the built-in class Throwable.
Throwable is at the top of the exception class hierarchy.
Throwable are two subclasses that partition exceptions into two distinct
branches.
This is also the class that you will subclass to create your own custom
exception types.
Exceptions of this type are automatically defined for the programs that
you write and include things such as division by zero and invalid array
indexing.
The other branch is topped by Error, which defines exceptions that are not
The diagram showing the exception hierarchy
class Exc
{
public static void main(String[]args)
{
int d,a;
try
{
d=0;
a=42/d;
System.out.println("This will notbe printed");
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
System.out.println("after the catch block");
}
}
o/p a=1
Array index oobjava.lang.ArrayIndexOutOfBoundsException: 42
after try catch block
If you try to compile this program, you will receive an error message
stating that the second catch statement is unreachable because the
exception has already been caught. Since ArithmeticException is a
subclass of Exception, the first catch statement will handle all Exception-
based errors, including ArithmeticException. This means that the second
catch statement will never execute. To fix the problem, reverse the order
of the catch statements
another example
class Nestedtry
{
public static void main(String[]args)
{
try
{
try
{
System.out.println("before the exception");
int b=39/0;
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
try
{
int []a=new int[4];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("The array index error");
}
}
catch(Exception e)
{
System.out.println("The outer exception ");
}
}
}
o/p: before the exception
Division by zero
The array index error
throw
So far, you have only been catching exceptions that are thrown by the Java
run time
system. However, it is possible for your program to throw an exception
explicitly, using the throw statement. The general form of throw is shown
here:
throw ThrowableInstance;
The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed. The nearest enclosing try block
is inspected to see if it has a catch statement that matches the type of
exception.
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
public static void main(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
System.out.println("caught" + e);
}
}
}
throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.
throw keyword is declared inside a method throws keyword is used with method signature
body. (method declaration).
We cannot throw multiple exceptions using We can declare multiple exceptions (separated
throw keyword. by commas) using throws keyword.
finally clause
A finally keyword is used to create a block of code that follows a try block.
A finally block of code is always executed whether an exception has
occurred or not. Using a finally block, it lets you run any cleanup type
statements that you want to execute, no matter what happens in the
protected code. A finally block appears at the end of catch block.
Class ExceptionTest
{
public static void main(String[] args)
{
int a[] = new int[2];
System.out.println("out of try");
try
{
System.out.println("Access invalid element"+ a[3]);
}
finally
{
System.out.println("finally is always executed.");
}
}
}
Multithreaded Programming
Java provides built-in support for multithreaded programming. A
multithreaded program contains two or more parts that can run
concurrently. Each part of such a program is called a thread, and each
thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking.
Java’s multithreading system is built upon the Thread class and its
companion interface, Runnable. Both are packaged in java.lang. Thread
encapsulates a thread of execution. To create a new thread, program will
either extend Thread or implement the Runnable interface.
The Thread class defines several methods that help manage threads. Here
are some of
Creating a Thread
Java defines two ways in which we can create a runnable object:
1.implement the Runnable interface. 2.Extend the Thread class
Both approaches still use the Thread class to instantiate, access, and
control the thread. The only difference is how a thread enabled class is
created.
The Runnable interface abstracts a unit of executable code. You can
construct a thread on any object that implements the Runnable interface.
Runnable defines only one method called run.
public void run()
Running State:
• Thread is executing
• The processor has given its time to the thread for its execution.
• The thread runs until it gives up control on its own or taken over
by other threads.
Blocked State:
• A thread is said to be blocked
• It is prevented to entering into the runnable and the running state.
• This happens when the thread is suspended, sleeping, or waiting in
order to satisfy certain requirements.
• A blocked thread is considered "not runnable" but not dead and
therefore fully qualified to run again.
• This state is achieved when we Invoke suspend() or sleep() or
wait() methods.
Dead State:
• Every thread has a life cycle.
• A running thread ends its life when it has completed executing its
run( ) method. It is a natural death.
• A thread can be killed in born, or in running, or even in "not
runnable" (blocked) condition.
• It is called premature death.
• This state is achieved when we invoke stop() method or the thread
completes it execution.
Blocking a Thread:
• A thread can also be temporarily suspended or blocked from
entering into the runnable and subsequently running state,
1. sleep(t) // blocked for ‘t’ milliseconds
2. suspend() // blocked until resume() method is invoked
3. wait() // blocked until notify () is invoked.
It is often useful to know when a thread has ended. The main thread
alive until the other threads ended.In those examples, main thread
sleep longer than the child threads that it spawned. This is, of course,
hardly a satisfactory or generalizable solution!
The difference is that it uses isAlive( ) to wait for the child threads
to terminate. Another way to wait for a thread to finish is to call join(
), shown here:
final void join( ) throws InterruptedException
Thread priority
• Each thread is assigned a priority, which affects the order in which
it is scheduled for running.
• Java permits us to set the priority of a thread using the setPriority()
method as follows:
ThreadName.setPriority(int Number);
}
public static void main(String args[]){
Threadpriority m1=new Threadpriority();
Threadpriority m2=new Threadpriority();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Set the priority of the threads
Java synchronization
• Generally threads use their own data and methods provided inside their
run() methods.
• But if we wish to use data and methods outside the thread’s run()
method, they may compete for the same resources and may lead to serious
problems.
• Java enables us to overcome this problem using a technique known as
Synchronization.
For ex.: One thread may try to read a record from a file while another is
still writing to the same file.
synchronized (lock-object)
{
.......... // code here is synchronized
}
Without Synchronization
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}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);
}
}
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();
}
}
5
100
10
200
15
300
20
400
25
500
The wait( ), notify( ), and notifyAll( ) methods are part of all objects because they
are implemented by the Object class. These methods should be called only from
within a synchronized context. Here is how they are used. When a thread is
temporarily blocked from running, it calls wait( ).
This causes the thread to go to sleep and the monitor for that object to be released,
allowing another thread to use the object. At a later point, the sleeping thread is
awakened when some other thread enters the same monitor and calls notify( ), or
notifyAll( ).
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
class Customer{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
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();
}}
O/P:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Thread groups:
Java thread group is implemented by java.lang.ThreadGroup class.
A ThreadGroup represents a set of threads. A thread group can also
include the other thread group. The thread group creates a tree in which
every thread group except the initial thread group has a parent.
Example
public class ThreadGroupDemo implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
Thread t1 = new Thread(tg1, runnable,"one");
t1.start();
Thread t2 = new Thread(tg1, runnable,"two");
t2.start();
Thread t3 = new Thread(tg1, runnable,"three");
t3.start();
System.out.println("Thread Group Name: "+tg1.getName());
tg1.list();
} }
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
There are many java daemon threads running automatically e.g. gc, finalizer etc.
public class TestDaemonThread1 extends Thread{
public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.start();//starting threads
t2.start();
t3.start();
} }
O/P: daemon thread work
user thread work
user thread work
Autoboxing:
The automatic conversion of primitive data types into its equivalent
Wrapper type is known as boxing and opposite operation is known as
unboxing. This is the new feature of Java5. So java programmer doesn't
need to write the conversion code.
Integer a3=5;//Boxing
System.out.println(a2+" "+a3);
}
}
O/P: Output:50 5
class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}
O/P : 50
Generics in Java:-
The Java Generics programming is introduced in J2SE 5 to deal with
type-safe objects. It makes the code stable by detecting the bugs at
compile time.
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);//compile time error
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
element is: jai
rahul
jai