Java Unit III
Java Unit III
Java Unit III
EXCEPTION HANDLING
What is Exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime. This leads to the abnormal termination of the program, which is not always
recommended.
Exception handling
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.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception handling.
1. try
2. catch
3. finally
4. throw
5. throws
try Block
Enclose the code that might throw an exception within a try block. If an exception occurs within
the try block, that exception is handled by an exception handler associated with it. The try block
contains at least one catch block or finally block.
try{
}catch(Exception_class_Name ref){}
try{
}finally{}
The try block within a try block is known as nested try block in java. Sometimes a situation may arise
where a part of a block may cause one error and the entire block itself may cause another error. In
such cases, exception handlers have to be nested.
try {
try {
int b = 39 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
try {
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
System.out.println("other statement");
} catch (Exception e) {
System.out.println("handeled");
System.out.println("normal flow..");
catch Block
Java catch block is used to handle the Exception. It must be used after the try block only. You can use
multiple catch block with a single try.
Syntax:
try
catch(Exception_type e)
try {
System.out.println("ArithmeticException caught!");
Output:
ArithmeticException caught!
throw Keyword
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;
throws Keyword
The Java throws keyword is used to declare an exception. It gives an information to the programmer
that there may occur an exception so it is better for the programmer to provide the exception handling
code so that normal flow can be maintained.
finally Block
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
Java finally block is always executed whether an exception is handled or not.
Java finally block follows try or catch block.
For each try block, there can be zero or more catch blocks, but only one finally block.
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).
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest
of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception
handling, the rest of the statement will be executed. That is why we use exception handling in Java.
Termination Model :
In resumptive model we may use a method call that want resumption like behavior. We may also
place the try block in a while loop that keeps re-entering the try block util the result is satisfactory.
In java, assume that, if we do not handle the exceptions in a program. In this case, when
an exception occurs in a particular function, then Java prints a exception message with the help of
uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us
to handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method known
dispatchUncaughtException( ), on the Thread class in which the exception occurs and terminates
the thread.
Example:
import java.util.Scanner;
public class UncaughtExceptionExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}}
Let's see an example where we place a try block within another try block for two different
exceptions.
public class NestedTryBlock
{
public static void main(String args[])
{
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}}
When any try block does not have a catch block for a particular exception, then the catch
block of the outer (parent) try block are checked for that exception, and if it matches, the catch
block of outer try block is executed.
If none of the catch block specified in the code is unable to handle the exception, then the
Java runtime system will handle the exception. Then it displays the system generated message for
that exception.
Throw keyword
The Java throw keyword is used to explicitly throw an exception. The general form of throw
is shown below:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
Primitive types, such as int or char, as well as non Throwable classes, such as String and Object,
cannot be used as exceptions.
There are two ways to obtain a Throwable object:
1. using a parameter in a catch clause
2. creating one with the new operator.
The following program explains the use of throw keyword.
public class TestThrow1
{ static void validate(int age){
try{
if(age<18)
throw new ArithmeticException(“not valid”);
else
System.out.println(“welcome to vote”);
}
Catch(ArithmeticException e)
{
System.out.println(“Caught inside ArithmeticExceptions.”); throw e; //
rethrow the exception
}
}
public static void main(String args[]){
try{
validate(13);
}
Catch(ArithmeticException e)
{
System.out.println(“ReCaught ArithmeticExceptions.”);
}
}
}
The flow of execution stops immediately after the throw statement and any subsequent
statements that are not executed. The nearest enclosing try block is inspected to see if it has a catch
statement that matches the type of exception. If it does find a match, control is trans- ferred to that
statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch
is found, then the default exception handler halts the program and printsthe stack trace.
The Throws/Throw Keywords
If a method does not handle a checked exception, the method must be declared using the
throws keyword. The throws keyword appears at the end of a method’s signature.
The difference between throws and throw keywords is that, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.
The following method declares that it throws a Remote Exception −
Example
import java.io.*;
public class throw_Example1 {
public void function(int a) throws RemoteException {
// Method implementation throw
new RemoteException();
} // Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the excep- tions
are declared in a list separated by commas. For example, the following method declares that it
throws a RemoteException and an ArithmeticException −
import java.io.*;
public class throw_Example2 {
public void function(int a) throws RemoteException,ArithmeticException {
// Method implementation
}
// Remainder of class definition
}
BUILT-IN EXCEPTIONS:
Built-in exceptions are the exceptions which are available in Java libraries. These excep- tions
are suitable to explain certain error situations. Below is the list of important built-in exceptions in
Java.
Exceptions Description
Arithmetic Exception It is thrown when an exceptional condition has oc-
curred in an arithmetic operation.
Array Index Out Of Bound It is thrown to indicate that an array has been accessed
Exception with an illegal index. The index is either negative or
greater than or equal to the size of the array.
ClassNotFoundException This Exception is raised when we try to access a class
whose definition is not found.
FileNotFoundException This Exception is raised when a file is not accessible
or does not open.
IOException It is thrown when an input-output operation failed or
interrupted.
InterruptedException It is thrown when a thread is waiting, sleeping, or do-
ing some processing, and it is interrupted.
NoSuchFieldException It is thrown when a class does not contain the field (or
variable) specified.
NoSuchMethodException It is thrown when accessing a method which is not
found.
NullPointerException This exception is raised when referring to the members of
a null object. Null represents nothing.
NumberFormatException This exception is raised when a method could not con-
vert a string into a numeric format.
RuntimeException This represents any exception which occurs during
runtime.
StringIndexOutOfBoundsEx- It is thrown by String class methods to indicate that an
ception index is either negative than the size of the string
class ArithmeticException_Demo {
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number by 0");
}}}
ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been accessed with
an illegal index. The index is either negative or greater than or equal to the size of the array.
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}}}
ClassNotFoundException : This Exception is raised when we try to access a class whose definition
is not found.
class A
{}
class B
{}
class MyClass {
public static void main(String[] args)
{
Object o = class.forName(args[0]).newInstance();
System.out.println("Class created for" + o.getClass().getName());
}}
FileNotFoundException : This Exception is raised when a file is not accessible or does not open.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String args[])
{
try {
File file = new File("E:// file.txt"); // Following file does not exist
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e) {
System.out.println("File does not exist");
}}}
import java.io.*;
class Sample {
public static void main(String args[])
{
FileInputStream f = null;
f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1) {
System.out.print((char)i);
}
f.close();
}}
NullPointerException : This exception is raised when referring to the members of a null object. Null
represents nothing
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}}
}
NumberFormatException : This exception is raised when a method could not convert a string into a
numeric format.
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
int num = Integer.parseInt("akhil"); // " akhil is not a number
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}}}
Methods Description
Throwable fillInStackTrace( ) Fills in the execution stack trace and returns a
Throwable object.
String getLocalizedMessage() Returns a localized description of the exception.
String getMessage() Returns a description of the exception.
void printStackTrace( ) Displays the stack trace.
String toString( ) Returns a String object containing a description of
the Exception.
StackTraceElement[ ]get Returns an array that contains the stack trace, one
StackTrace( ) element at a time, as an array of StackTraceEle-
ment.
THREAD
Thread is a lightweight process, the 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 uses a shared memory area.
Terminated(Dead)
A thread is in terminated or dead state when its run() method exits. Because it exits normally.
This happens when the code of thread has entirely executed by the program.
Because there occurred some unusual erroneous event, like segmentation fault or an
unhandled exception.
A thread that lies in terminated state does no longer consumes any cycles of CPU.
public void start(): starts the execution of the thread. JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
public void join(long miliseconds): waits for a thread to die for the specified milliseconds
public int getPriority(): returns the priority of the thread.
public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public static boolean interrupted(): tests if the current thread has been interrupted
MULTITHREADING:
A thread is a basic execution unit which has its own program counter, set of the register and
stack. But it shares the code, data, and file of the process to which it belongs. A process can have
multiple threads simultaneously, and the CPU switches among these threads so frequently making an
impression on the user that all threads are running simultaneously.
Advantage of the Multithreading
It enables you to write very efficient programs that maximizes the CPU utilization and
reduces the idle time.
Most I/O devices such as network ports, disk drives or the keyboard are much slower than
CPU
A program will spend much of it time just send and receive the information to or from the
devices, which in turn wastes the CPU valuable time.
By using the multithreading, your program can perform another task during this idle time.
For example, while one part of the program is sending a file over the internet, another part can
read the input from the keyboard, while other part can buffer the next block to send.
It is possible to run two or more threads in multiprocessor or multi core systems
simultaneously.
MULTI-TASKING
Multitasking is when a single CPU performs several tasks (program, process, task, threads) at the
same time. To perform multitasking, the CPU switches among these tasks very frequently so that user
can interact with each program simultaneously
In a multitasking operating system, several users can share the system simultaneously. CPU rapidly
switches among the tasks, so a little time is needed to switch from one user to the next user. This puts
an impression on a user that entire computer system is dedicated to him.
When several users are sharing a multitasking operating system, CPU scheduling and
multiprogramming makes it possible for each user to have at least a small portion of Multitasking OS
and let each user have at least one program in the memory for execution.
Types of multitasking:
Executing various jobs together where each job is a separate independent operation is called process-
based multitasking. It is best suitable for the operating system level.
The main goal of multitasking is to make or do a better performance of the system by reducing
response time.
CREATING A THREAD:
A thread is a lightweight process. Every java program executes by a thread called the main
thread. When a java program gets executed, the main thread created automatically. All other threads
called from the main thread. The java programming language provides two methods to create threads,
and they are listed below.
The java contains a built-in class Thread inside the java.lang package. The Thread class contains all
the methods that are related to the threads.
Step-1: Create a class as a child of Thread class. That means, create a class that extends
Thread class.
Syntax:
Class udef extends Thread
{ // statements
Public void run ( )
{ // code for thread
}
// statements
}
Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
Syntax:
Public void run ( )
{
// thread code here
}
Step-3: Create the object of the newly created class in the main( ) method.
Syntax:
udef thobjname = new udef( );
thobjname.start ( );
Step-4: Call the start( ) method on the object created in the above step.
Example program:
import java.io.*;
import java.lang.*;
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("From Threaad 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 Threaad 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 Threaad C :k="+k);
}
System.out.println("Exit from Thread C");
}}
class ThreadTest
{
public static void main(String args[])
{
System.out.println("main thread started");
A a=new A();
a.start();
B b=new B();
b.start();
C c=new C();
c.start();
System.out.println("main thread ended");
}}
Output:
Syntax:
Step-2: Override the run( ) method with the code that is to be executed by the thread. The
run( ) method must be public while overriding.
Syntax:
Public void run ( )
{
// thread code here
}
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Create the Thread class object by passing above created object as parameter to the
Thread class constructor.
Syntax:
udef testx = new udef( );
Thread testthread = new Thread (testx);
Thestthread.start ( );
Step-5: Call the start( ) method on the Thread class object created in the above step.
Whenever we want to stop a thread from running state by calling stop() method
of Thread class in Java.
Syntax
Threadobject.stop ( );
Example program:
class x implements Runnable
{
public void run()
{
for(int i=0;i<=5;i++)
System.out.println("The Thread x is:"+i);
System.out.println("End of the Thread x");
}}
class RunnableTest
{
public static void main(String args[])
{
x r=new x();
Thread threadx=new Thread(r);
threadx.start();
System.out.println("The end of the main thread");
}}
Output:
THREAD PRIORITY:
In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
Syntax:
Threadname.setpriority(int number (or) priority constants);
The Thread class also contains three constants that are used to set the thread priority, and they are
listed below.
Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);
Example Program:
class PThread1 extends Thread
{
public void run()
{
System.out.println(" Child 1 is started");
}}
class PThread2 extends Thread
{
public void run()
{
System.out.println(" Child 2 is started");
}}
class PThread3 extends Thread
{
public void run()
{
System.out.println(" Child 3 is started");
}}
class PTest
{
public static void main(String args[])
{
PThread1 pt1=new PThread1();
pt1.setPriority(1); PThread2
pt2=new PThread2();
pt2.setPriority(9);
PThread3 pt3=new PThread3();
pt3.setPriority(6);
pt1.start();
pt2.start();
pt3.start();
System.out.println("The pt1 thread priority is :"+pt1.getPriority());
}}
Thread Synchronization:
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.
When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.
Synchronization is mainly used
To prevent thread interference
To prevent consistency problem
Types:
There are 2 types of thread synchronization
Mutual exclusive
Inter thread communication
Using Synchronized Methods:
INTER-THREAD COMMUNICATION
Inter-process communication (IPC) is a mechanism that allows the exchange of data between
processes. If two or more Threads are communicating with each other, it is called "inter thread"
communication. Using the synchronized method, two or more threads can communicate indirectly.
Through, synchronized method, each thread always competes for the resource. This way of competing
is called polling.
Java addresses this polling problem, using via wait(), notify(), and notifyAll() methods.
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( ).
notify( ) wakes up a thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will be
granted access.