JAVA Unit 4
JAVA Unit 4
JAVA Unit 4
Exception handling:
Exception definition, benefits of exception handling,
exception hierarchy, usage of try, catch, throw, throws
and finally, built in exceptions, creating user defined
exceptions.
Multi-Threading:
Thread definition, types of multitasking, uses of
multitasking, thread life cycle, creating threads using
Thread class and Runnable interface, synchronizing
threads, daemon thread.
1
Types of errors
• Compile-time errors
• Run-time errors
2
Compile-Time Errors
Missing semicolons.
Missing brackets in classes and methods.
Misspelling of identifiers and keywords.
Missing double quotes in strings.
Use of undeclared variables.
Bad references to objects.
And so on.
3
Run-Time Errors
Dividing an integer by zero.
Accessing an element that is out of the bounds of
an array.
Attempting to use a negative size of an array.
Converting invalid string to a number.
Accessing a character that is out of bounds of a
string.
Using a null reference to access a method or a
variable.
Missing input file.
And so on.
4
Exception
An exception is an abnormal condition that
arises in a code at run time.
(or) An exception is a run-time error.
6
Benefits of exception handling
7
Exception-Handling
When an exception arises, an object representing that
exception is created and thrown in the method that
caused the error.
8
Java exception handling is managed by via five keywords:
try, catch, throw, throws, and finally.
Program statements which might generate exceptions are
kept inside a try block. (Program statements to monitor
are contained within a try block.)
If an exception occurs within the try block, it is thrown.
Code within catch block catch the exception and handle it.
System generated exceptions are automatically thrown by
the Java run-time system.
To manually throw an exception, use the keyword throw
Any exception that is thrown out of a method must be
specified as such by a throws clause.
Statements contained in the finally block will be executed,
regardless of whether or not an exception is raised.
9
General form of an exception-handling block
try
{
// block of code to monitor for errors try Block
} Statements that
catch (ExceptionType1 exOb) Causes an exception
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{ catch Block
// exception handler for ExceptionType2 Statement that
} handles the exception
//…
finally
{
// block of code to be executed after try/catch block ends
}
10
Java Exception class hierarchy
EOFException
IOException
FileNotFoundException
Exception
ArithmeticException
ArrayIndexOutOfBoundsException
RuntimeException
StringIndexOutOfBoundsException
Object Throwable
NumberFormatException
NullPointerException
VirtualMachineError
Error Ex: Stack overflow
Checked
Unchecked
11
All exception types are subclasses of the
built-in class Throwable
Throwable has two subclasses, they are
– Exception
• Represents exceptional conditions that an user
program might want to catch.
Ex:- IOExceptions, RuntimeExceptions etc.
– Error
• Represents exceptional conditions that are not
expected to be caught by user program.
i.e. Stack overflow
12
• IOExceptions:-
– The Subclasses of IOException represent
errors that can occur during the processing of
input and output statements.
• RuntimeExceptions:-
– The subclasses of RuntimeException represent
conditions that arise during the processing of
the bytecode that represent a program.
13
Categories Of Exceptions
Unchecked exceptions
Checked exception
14
Unchecked Exceptions
The compiler doesn’t force you to catch
them if they are thrown.
– No try-catch block required by the compiler
Examples:
– NullPointerException,
IndexOutOfBoundsException,
ArithmeticException…
15
NullPointerException example:
class UncheckExce
{
public static void main(String args[])
{
int arr[] =null;
arr[0] = 1; NullPointerException
System.out.println(arr[0]);
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at UncheckExce.main(UncheckExce.java:6)
16
IndexOutOfBoundsException example:
class UncheckExce
{
public static void main(String args[])
{
int arr[] = new int[4];
for (int i = 0; i <= 4; i++)
ArrayIndexOutOfBoundsEx
arr[i] = i; ception
}
(when i = 4)
}
Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
at UncheckExce.main(UncheckExce.java:7)
17
Checked Exceptions
The compiler gives an error if we do not
catch these exceptions
The compiler force you to catch them if
they are thrown
Must be handled
– You must use a try-catch block or throws
Example:
– IOException etc.
18
IOException Example
import java.io.*;
public class KeyboardReading5
{
public static void main(String args[])
{
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter name: ");
String str = dis.readLine();
System.out.println("Name:"+str);
}
}
Error
20
The Java Stack Trace
2 2 2 m2 2 2 2
1 1 m1 1 m1 1 m1 1 1
0 main 0 main 0 main 0 main 0 main 0
Output:
Starting Main method
Method One - m1
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Trace.m2(Trace.java:14)
at Trace.m1(Trace.java:9)
at Trace.main(Trace.java:4) 22
Using try and catch
The catch block should follow immediately the try
block.
26
Example:
class MultiCatch
{
public static void main(String args[])
{
try Output:
{ D:\javap>java MultiCatch
int b = 42 / 0; Divide by 0: java.lang.ArithmeticException: /
int c[] = { 1 }; by zero
c[42] = 99; After try/catch blocks.
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
27
Example:
class MultiCatch
{
public static void main(String args[])
{ Output:
try D:\javap>java MultiCatch
{ Array index oob:
int b = 42 / 1; java.lang.ArrayIndexOutOfBoundsException:
int c[] = { 1 }; 42
c[42] = 99; After try/catch blocks.
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
} 28
Caution
Remember that, exception subclass must come
before any of of their superclasses
Because, a catch statement that uses a superclass
will catch exceptions of that type plus any of its
subclasses. So, the subclass would never be
reached if it comes after its superclass
For example, ArithmeticException is a subclass
of Exception
Moreover, unreachable code in Java generates
error.
29
class SuperSubCatch
{
public static void main(String args[])
{
try
{
int a = 0;
int b = 42 / a;
}
catch(Exception e)
{
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e)
{ // ERROR - unreachable
System.out.println("This is never reached.");
}
}
Output: SuperSubCatch.java:22: exception java.lang.ArithmeticException has
already been caught catch(ArithmeticException e)
^
30
1 error
Nested try Statements
A try statement can be inside the block of another try.
32
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
33
throw
So far, you have only been catching exceptions that are
thrown by the Java run-time system.
class NestTry
{
public static void main(String args[])
{
try
{
int a = args.length;
int b;
if(a==0) throw new ArithmeticException("Divide by Zero");
else
b = 42 / a;
System.out.println(b);
}
35
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
Output:
36
new is used to construct an instance of
ArithmeticException.
38
Example:
import java.io.*;
class MyException{
public static void main(String args[]){
try{
checkEx();
} catch( IOException ioe){
System.out.println(" File Not Found ");
}
}
public static void checkEx() throws IOException{
40
Syntax:
try
{
…..
…..
}
catch ( …….)
{
….
….
}
catch ( …….)
{
….
….
}
finally
{
…
…
}
41
42
43
44
Difference between final, finally and finalize
Finalize is used to
Release the resources
held by the object just
before the object is
deleted by the
garbage collector.
45
Output : finalize called
46
Java’s Built-in Exceptions
Java defines several exception classes in java.lang package
and java.io package.
Unchecked RuntimeException subclasses
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
Exception Meaning
49
User-defined exceptions are created by
extending Exception class.
50
The Methods Defined by Throwable
Method Description
void printStackTrace( ) Displays the stack trace.
51
Example:
class MyException extends Exception
{
private String desc;
MyException(String a)
{
desc = a;
}
public String toString()
{
return "MyException:" + desc;
}
public String getMessage() { return desc;}
}
class ExceptionDemo
{
52
public static void main(String args[])
{
int a=0,d;
try
{
if (a==0) throw new MyException("/ by zero");
else
d=42/a;
System.out.println(d);
}
catch(MyException e)
{
System.out.println("Caught " + e);
System.out.println(e.getMessage());
}
}
}
Output: Caught MyException: / by zero
/ by zero
53
Multithreaded Programming
Thread is a part of the program
Multitasking: Executing two or more programs
concurrently
Multithreading: Executing multiple parts of a
single program concurrently
Types of Multitasking
Process Based
Thread Based
54
Process Based Multitasking
The process-based multitasking is the feature that allows
your computer to run two or more programs concurrently.
55
Process Based Multi Tasking
Processor
The Operating
System assigns
processor time to
each task
56
Thread Based Multitasking
The thread-based multitasking is the feature that
allows your computer to run two or more parts of
a program concurrently.
57
Thread Based Multitasking
Task A
T2
Processor T1
T0
A Threading
library creates
threads and
assigns processor
time to each
thread
58
Multitasking Improves Performance
Single task
p1
Two tasks
59
Context switch
60
Difference b/w Multithreading and Multitasking
Multithreading Multitasking
It supports execution of multiple It supports execution of multiple
parts of a single program simultaneously programs simultaneously.
All threads share common address space Each process has its own
address space
61
Thread Life Cycle( States)
62
Thread States
When a thread is first created, it does not exist as an
independently executing set of instructions. Instead, it
is a template/structure from which an executing
thread will be created. This state is refer to as born
state.
When the thread start method is called, the thread
enters into the ready state.
When the system assigns a processor to the thread,
the thread enters into the running state.
A thread enters into the dead state when it finishes its
execution(when its run method completes or
terminates). 63
The running thread will enter into the block state
when it issues an input or output request.
The running thread will enter into the waiting state
when wait method is called.
• The thread in the waiting state will become ready
when notify method is called.
• Every thread in the waiting state will become
ready when notifyAll method is called.
The running thread will enter into the sleeping state
when sleep method is called.
64
Thread priorities
Every thread has a priority( integer value) which can be
increased or decreased by calling the setPriority() method.
– If two threads with the same priority are competing for CPU cycles,
those threads are time-sliced or time-shared automatically in round-
robin fashion (Windows 98).
66
The Thread Class and the Runnable
Interface
67
Methods Defined by the Thread class
public class Thread {
public Thread(Runnable R); // Thread R.run()
public Thread(Runnable R, String threadName);
public void start(); // begin thread execution
public void run(); // Entry point for the thread.
public String getName(); // obtain a thread’s name
public boolean isAlive(); // Determine if a thread is still running.
final public void join(); // Wait for a thread to terminate.
public void setName(String name); // sets name to the thread
public void setPriority(int level); // sets priority to the thread
public static Thread currentThread(); //references to a main thread
public static void sleep(long milliseconds); //Suspend a thread for a
period of time.
...
}
68
The Main Thread
When a Java program starts up, one thread begins running
immediately.
This is usually called the main thread of your program,
because it is the one that is executed when your program
begins.
The main thread is important for two reasons:
It is the thread from which other “child” threads will be
generated.
Often it must be the last thread to finish execution.
69
Although the main thread is created automatically, it can
be controlled through Thread object.
We can obtain a reference to a main thread by calling the
method currentThread( ), which is a public static
member of Thread.
70
Ex:-
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Name of the thread: " + t.getName());
71
Creating Threads in java
Threads are implemented in the form of
objects that contain a method called run( ).
Output:
this thread is running ...
74
Example2:
class ThreadTest
class MyThread implements Runnable {
{ public static void main( String args[ ] ) throws
public void run() InterruptedException
{ {
System.out.println("Main thread is running");
System.out.println(" \t\t\tchild thread is running");
76
II method: Extending Thread class
1. Declare a class that extends a Thread class
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
2. Create your thread class instance in main:
MyThread thr1 = new MyThread();
3. Start Execution of threads:
thr1.start();
77
Ex:-
class MyThread extends Thread
{
public void run()
{
System.out.println(" this thread is running ... ");
}
}
class ThreadTest
{
public static void main(String [] args )
{
MyThread thr1 = new MyThread();
// due to extending the Thread class (above)
// I can call start(), and this will call
// run(). start() is a method in class Thread.
thr1.start();
}
}
Output:
this thread is running …
78
join()
79
Creates thread t
Main thread
Calls t.join()
Main thread
resumes
80
Example:
class ThreadTest
class MyThread implements Runnable {
{ public static void main( String args[ ] ) throws
public void run() InterruptedException
{ {
System.out.println("Main thread is running");
System.out.println(" \t\t\tchild thread is running");
81
Output:
82
Synchronization
When two or more threads need access to a shared
resource, the resource will be used by only one thread at a
time is called synchronization.
83
Ex:-
Booking
agent 1
Booking
agent 2 ….. Booking
agent n
Check availability
Reserve seat
Check availability
Reserve seat Check availability
Reserve seat
Seat reservation
database
84
Using Synchronized Methods
Every object with synchronized method is a monitor.
85
Understanding the problem without Synchronization
In this example, there is no synchronization, so output is
inconsistent
class Table
{
synchronized void printTable(int n)
{
for(int i=1; i<=5; i++)
{
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
86
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
87
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
88
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
• Output with synchronized method
5 10 15 20 25 100 200 300 400 500 89
Inter-thread communication in Java
Inter-thread communication or Co-operation is all about
allowing synchronized threads to communicate with each
other.
90
wait( ) - Tells the calling thread to give up the monitor
and go to sleep until some other thread enters the
same monitor and calls notify( ).
91
Example:
class Test {
boolean flag = false;
public synchronized void question(String msg) {
if (flag) {
try {
wait();
} catch (InterruptedException e) { }
}
System.out.println(msg);
flag = true;
notify();
} 92
public synchronized void answer(String msg) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) { }
}
System.out.println(msg);
flag = false;
notify();
}
}
93
class T1 extends Thread
{
Test m;
String[] s1 = { "q1.........?", "q2.......... ?",
"q3................?" };
public T1(Test m) { this.m = m; }
public void run() {
for (int i = 0; i < s1.length; i++) {
m.question(s1[i]);
}
}
}
94
class T2 extends Thread
{
Test m;
String[ ] s2 = { "a1..........", "a2...............",
"a3............." };
public T2(Test m) { this.m = m; }
public void run() {
for (int i = 0; i < s2.length; i++) {
m.answer(s2[i]);
}
}
}
95
public class TestThread {
public static void main(String[] args) {
Test m = new Test();
T1 q=new T1(m);
T2 a=new T2(m);
q.start();
a.start();
}
Output:
}
q1.........?
a1..........
q2.......... ?
a2...............
q3...............?
a3.............
96
Daemon Threads
Threads that run in the background and provide
services to an application are called daemon threads.
– There are many java daemon threads running
automatically, example , the garbage collector.
Normally when a thread is created in Java, by default
it is an user defined thread.
JVM terminates the daemon thread if there are no
user threads.
Any thread can be converted into a daemon thread
simply by passing true to the setDaemon() method.
97
Example:
class DThread extends Thread
{
public void run()
{
while (true)
{
try {
Thread.sleep(500);
} catch (InterruptedException x) { }
System.out.println("\t\t\t Daemon Thread Running");
}
}
}
98
class DaemonThread
{
public static void main(String[] args)
{
System.out.println("Entering main Method");
DThread dt = new DThread();
dt.setDaemon(true);
dt.start();
try {
Thread.sleep(3000);
} catch (InterruptedException x) { }
100