Java Exception Handling Explained
Java Exception Handling Explained
1. Exception:
• Exception is a problem that arises at the time of program execution.
• When an exception occurs, it disrupts the program execution flow.
• When an exception occurs, the program execution gets terminated, and the system
generates an error. We use the exception handling mechanism to avoid abnormal
termination of program execution.
1
Java programming language has the following class hierarchy to support the exception handling
mechanism.
1.2.1 try…catch
The try and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception.
The keyword catch is used to define a block of code that handles the exception occurred in
the respective try block..
2
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.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
cannot use try without at least one catch, and catch alone can be used (catch without try is not
allowed).
Syntax
try
{
...
code to be tested
...
}
catch (ExceptionType object)
{
...
code for handling the exception
...
}
Example:
class TryCatchExample
{
public static void main(String[] args)
{
try
{
int a = 10;
int b = 0;
int c = a / b;
[Link](a + "/" + b +" = " + c);
}
catch(ArithmeticException ae)
{
[Link]("Value of divisor can not be ZERO");
}
}
}
when an exception occurs in the try block the execution control transferred to the catch
block and the catch block handles it.
3
1.2.2 Multiple catch clauses
In java programming language, a try block may have one or more number of catch blocks. That
means a single try statement can have multiple catch clauses.
When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.
Example:
class TryCatchExample
{
public static void main(String[] args)
{
try
{
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae)
{
[Link](" Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie)
{
[Link]("ArrayIndexOutOfBoundsException has
occured.");
}
catch(Exception e)
{
[Link](" Unknown exception has occured.");
}
}
}
4
1.2.3 throw Keyword
The throw keyword is used to explicitly throw an exception.
The throw keyword must be used inside the try block. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
Using throw keyword only one exception can be thrown. The throw keyword must followed
by an throwable instance.
The following is the general syntax for using throw keyword in a try block.
throw new ThrowableInstance;
Example:
class Test
{
static void check(int age)
{
if(age<18)
throw new ArithmeticException("Not Elgible to Vote");
else
[Link]("Elgible to Vote");
}
throws keyword allows throw an exception from a method. If there is chance of raise any checked
exception, compulsory we have to handle otherwise compile time error we will get.
5
In two ways we can handle this type of exceptions
import [Link].*;
class throwsException
{
public static void main(String args[]) throws FileNotFoundException
{
FileReader fr=new FileReader(" [Link]");
}
}
throws keyword will not handle the error, it’s convinced the compiler and avoids the
abnormal termination of a program.
6
Syntax 1:
try
{
...
}
finally
{
....
}
Syntax 2:
try {
...
}
catch(Throwable e)
{
...
}
finally
{
....
}
Example:
class finallyExample
{
public static void main(String args[])
{
try
{
[Link](10/0);
}
catch(ArithmeticException ae)
{
[Link]("Divisble by zero");
}
finally
{
[Link]("Finally Block");
}
try
{
[Link]("try Block");
}
finally
{
[Link]("Java Finally Block");
7
}
}
}
To create our own exception class simply create a class as a subclass of built-in Exception class.
We may create constructor in the user-defined exception class and pass a string to Exception class
constructor using super(). We can use getMessage() method to access the string.
8
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5, y=1000;
try
{
float z= (float) x/ (float) y;
if(z<0.01)
{
throw new MyException(" Number is too
small");
}
}
catch(MyException e)
{
[Link]("Caught my exception");
[Link]([Link]());
}
}
}
9
Multithreading in java
2.1 Introduction
The java programming language allows us to create a program that contains one or more parts
that can run simultaneously at the same time. This type of program is known as a
multithreading program.
Each part of this program is called a thread. Every thread defines a separate path of execution
in java.
A thread is explained in different ways, and a few of them are as specified below.
• Process-based multitasking
• Thread-based multitasking
It allows the computer to run two or It allows the computer to run two or more
more programs concurrently threads concurrently
In this process is the smallest unit. In this thread is the smallest unit.
Process is a larger unit. Thread is a part of process.
Process is heavy weight. Thread is light weight.
Process requires separate address
Threads share same address space.
space for each.
Process never gain access over idle
Thread gain access over idle time of CPU.
time of CPU.
Inter process communication is Inter thread communication is not
expensive. expensive.
10
2.2 Creating threads in Java
In java, 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.
11
Example 1:
class Single extends Thread
{
public void run()
{
[Link]("Sample Thread Program");
}
}
class SampleThread
{
public static void main(String args[])
{
Single s=new Single();
[Link]();
}
}
Example 2:
class SampleThread extends Thread
{
public void run()
{
[Link]("Thread is under Running...");
for(int i= 1; i<=10; i++)
{
[Link]("i = " + i);
}
}
}
class MyThread
{
public static void main(String[] args)
{
SampleThread t1 = new SampleThread();
[Link]("Thread about to start...");
[Link]();
}
}
12
2.2.2 Implementing Runnable interface
The java contains a built-in interface Runnable inside the [Link] package.
The Runnable interface implemented by the Thread class that contains all the methods that
are related to the threads.
To create a thread using Runnable interface, follow the step given below.
Step-1: Create a class that implements Runnable interface.
Syntax:
class NewThread implements Runnable
{
......
......
......
}
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( )
{
......
//code segment providing the functionality of thread
.....
}
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.
Step-5: Call the start( ) method on the Thread class object created in the above step.
Example:
In java, a thread goes through different states throughout its execution. These stages are called
thread life cycle states or phases.
14
2.3.1 New:
In this state, a new thread is created but not started. This state is also known as Born state.
Syntax:
Thread obj = new Thread();
The above statement is responsible for creating a new Thread object At this state , we can do only
one of the following things with it:
• Schedule it for running using start() method
• Kill it using stop() method
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor.
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This
state is also known as a Ready state.
[Link]();
4.3.2 Running:
Running means that the processor has given its time to the thread for its execution.
When a thread calls run( ) method, then the thread is said to be Running. The run( )
method of a thread called automatically by the start( ) method.
A thread which is in any of these three states can be assumed to be in ‘not runnable’ state.
These three states are WAITING, TIMED_WAITING, and BLOCKED.
Waiting : In this state, a thread is waiting indefinitely for another thread to perform a particular
action (i.e., notify). Threads can move into this state either by calling the methods
[Link]() (without time out) or [Link]() (without time out).
Timed_Waiting : In this state, the thread is waiting for another thread to perform an action
(notify) up to a specified waiting time. A thread can get into this state by calling
either of these methods: [Link](), [Link](), and
[Link]()
(all these methods should be called with time out specified).
15
Blocked : In this state, a resource cannot be accessed because it is being used by another
thread.A thread can get into this state by calling [Link]() method.
4.3.4 Terminated
A thread in the Running state may move into the dead state due to either its
execution completed or the stop( ) method called. The dead state is also known as the
terminated state.
Return
Method Description
Value
16
Example :
}
[Link](i);
}
}
}
class ThreadMethods
{
public static void main(String args[])
{
Sample s1=new Sample();
Sample s2=new Sample();
[Link]("Id = "+[Link]());
[Link]("Name of the Thread s1 = "+[Link]());
[Link]("Thread One");
[Link]("Name of the Thread after Changing =
"+[Link]());
[Link]("Priority of Thread s1 = "+[Link]());
[Link]("Priority of Thread s2 = "+[Link]());
[Link](6);
[Link]("After Changing Priority of Thread s1 =
"+[Link]());
[Link]();
}
}
17
Example Program on Join Method :
class Sample extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)
{
try
{
[Link](1000);
}
catch(InterruptedException ie)
{
}
[Link](i);
}
}
}
class ThreadMethods
{
public static void main(String args[])
{
Sample s1=new Sample();
Sample s2=new Sample();
[Link]();
try
{
[Link]("Thread1 Running");
[Link]();
[Link]("Thread1 Ends");
}
catch(InterruptedException e)
{
}
[Link]("Thread2 Running");
[Link]();
}
}
18
2.4 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.
In java, the thread priority range from 1 to 10. Priority 1 is considered as the lowest priority,
and priority 10 is considered as the highest priority.
The thread with more priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and they
are listed below.
19
2.5 SYNCHRONIZATION
The java programming language supports multithreading. The problem of shared resources
occurs when two or more threads get execute at the same time. In such a situation, we need
some way to ensure that the shared resource will be accessed by only one thread at a time,
and this is performed by using the concept called synchronization.
The synchronization is the process of allowing only one thread to access a shared resource at
a time.
Using the mutual exclusion process, we keep threads from interfering with one another while
they accessing the shared resource. In java, mutual exclusion is achieved using the following
concepts.
• Synchronized method
• Synchronized block
In the above image, initially the thread-1 is accessing the synchronized method and other
threads (thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.
20
Syntax for Synchronized Method:
synchronized Methodname()
{
……..
// method Body
}
Example :-
class Display
{
synchronized void printTable(int n)
{
for(int i=1;i<=10;i++)
{
[Link](n+"*"+i+"="+i*n);
}
}
}
class Mythread extends Thread
{
Display d;
int num;
Mythread(Display d, int num)
{
this.d=d;
[Link]=num;
}
public void run()
{
[Link](num);
}
}
class ThreadSync
{
public static void main(String
args[])
{
Display d=new Display();
Mythread m1=new Mythread(d,5);
Mythread m2=new Mythread(d,10);
[Link]();
[Link]();
}
}
21
2.5.2 Synchronized Block / Statements
The synchronized block is used when we want to synchronize only a specific sequence of lines
in a method.
For example, let's consider a method with 20 lines of code where we want to synchronize only
a sequence of 5 lines code, we use the synchronized block.
Syntax:
Example:
class Test
{
public void show()
{
synchronized(this)
{
for(int i=0;i<5;i++)
{
[Link](i);
}
}
for(int i=20;i<25;i++)
{
[Link](i);
}
}
}
class MyThread extends Thread
{
Test T;
MyThread(Test T)
{
this.T=T;
}
public void run()
{
22
[Link]();
}
}
class SyncMethod
{
public static void main(String args[])
{
Test obj=new Test();
MyThread t1=new MyThread(obj);
MyThead t2=new MyThread(obj);
[Link]();
[Link]();
}
}
23
3. Input/Output
3.1 Introduction
The two most important parts of a computer are input and output. Input/output classes form
the core of any programming language.
The [Link] package provides separate classes for reading and writing data (byte and
character data). The java I/O facility is based on streams.
The Stream is defined in the [Link] package.
Stream is a continuous flow of data. Java provides two types of streams, and they are as follows.
• Byte Stream
• Character Stream
Byte stream classes deal with reading and writing of bytes to files, socket, etc.
Character stream classes deal with reading and writing characters to files, socket, etc.
The [Link] package contains two top level byte stream abstract classes :
[Link] (for reading bytes) and [Link] (for writing
bytes).
The [Link] package also contains two other level character stream abstract classes:
[Link] (for reading characters) and [Link] (for writing characters).
24
The
boolean It returns true if the named file does not exist and was
createNewFile() successfully created; false if the named file already
exists.
boolean delete() It deletes the file or directory. And returns true if and
only if the file or directory is successfully deleted;
false otherwise.
Example Program:
import [Link].*;
class FileDemo
{
public static void main(String args[])
{
File f = new File("D:\\[Link]");
[Link]("Existance : " + [Link]());
[Link]("Read mode : " + [Link]());
[Link]("Write mode : " + [Link]());
[Link]("Executable File : " + [Link]());
[Link]("Name of the file : " + [Link]());
[Link]("Parent name : " + [Link]());
[Link]("path of the File : " + [Link]());
[Link]("Hidden File : " + [Link]());
[Link]("Length of the File : " + [Link]());
[Link]("Last Modified : " + [Link]());
[Link]("It is a File : " + [Link]());
}
}
26
3.3 File Reading & Writing in Java
In java, there multiple ways to read data from a file and to write data to a file. The most
commonly used ways are as follows.
The InputStream class has defined as an abstract class, and it has the following methods
Method Description
int available() It returns the number of bytes that can be read
from the input stream.
int read() It reads the next byte from the input stream.
int read(byte[] b) It Reads up to [Link] bytes of data from this
input stream into the byte array b.
int read(byte b[], Reads m bytes into b starting from nth byte
int n, int m)
void close() It closes the input stream and also frees any
resources connected with this input stream.
long skip(long n) Skips over n bytes from the input stream
27
The OutputStream class has defined as an abstract class, and it has the following methods.
Method Description
void write(int n) It writes byte(contained in an int) to the
output stream.
void write(byte[] It writes a whole byte array(b) to the output
b) stream.
void write(byte[] Writes m bytes from array b starting from nth
b, int n, int m) byte
void flush() It flushes the output steam by forcing out
buffered bytes to be written out.
void close() It closes the output stream and also frees any
resources connected with this output stream.
28
File Handling using Character Stream
In java, we can use a character stream to handle files. The character stream has the following
built-in classes to perform various operations on a file.
• FileReader - It is a built-in class in java that allows reading data from a file. This class has
implemented based on the character stream. The FileReader class provides a
method read() to read data from a file character by character.
• FileWriter - It is a built-in class in java that allows writing data to a file. This class has
implemented based on the character stream. The FileWriter class provides a
method write() to write data to a file character by character.
29
3.4 Scanner Class
The Scanner is a built-in class in java used for read the input from the user in java
programming. The Scanner class is defined inside the [Link] package.
Hence to use the Scanner class in your program, you need to import this package as follows.
import [Link].*
OR
import [Link];
The Scanner class provides the easiest way to read input in a Java program.
The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter
is whitespace.
Syntax :-
Scanner scannerObject = new Scanner([Link]);
Method Description
void close() Closes this scanner.
Returns true if this scanner has another
boolean hasNext()
token else false.
Returns true if the next token matches
boolean hasNext(Pattern p)
the specified pattern (p).
Returns true if the next token matches
boolean hasNext(String p)
the pattern in the specified string (p).
Returns true if the next token in this
boolean hasNextBoolean() input can be interpreted as a Boolean
value
Returns true if the next token in this
boolean hasNextByte() input can be interpreted as a byte
value.
Returns true if the next token in this
boolean hasNextDouble() input can be interpreted as a double
value.
Returns true if the next token in this
boolean hasNextFloat()
input can be interpreted as a fl oat.
Returns true if the next token in this
boolean hasNextInt()
input can be interpreted as an int.
Returns true if there is another line
boolean hasNextLine()
in the input.
30
Returns true if the next token in this
boolean hasNextLong() scanner’s input can be interpreted as a
long
Returns true if the next token in this
boolean hasNextShort() scanner’s input can be interpreted as a
short.
Returns the next complete token from
String next()
this scanner.
String next(Pattern Returns the next token if it matches the
pattern) specified pattern.
Scans the next token of the input into
boolean nextBoolean()
a boolean value and returns that value.
Returns the next token of the input as
byte nextByte()
a byte.
Returns the next token of the input as
double nextdouble()
a double.
Returns the next token of the input as
float nextFlot()
a float.
Returns the next token of the input as
short nextInt()
an int
Advances this scanner past the current
short nextLine()
line and returns the input as a string
Returns the next token of the input as
short nextLong()
a long.
Returns the next token of the input as
short nextShort()
a short
Sets the delimiting pattern for scan to
Scanner useDelimiter
pattern constructed from the specified
(String pattern)
string.
Example:-
import [Link].*;
class ScannerInput
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter a String");
String str=[Link]();
[Link]("Enter Integer number");
int num=[Link]();
[Link]("Enter Float number");
float real=[Link]();
[Link]("\n------------------------------------------");
[Link]("Entered String is "+ str);
31
[Link]("Entered Integer Number is "+ num);
[Link]("Entered Float Number is "+ real);
}
}
32
Example Program on Buffered Output and Input class :
import [Link].*;
class BufferedIOExample
{
public static void main(String args[])throws IOException
{
FileOutputStream fout=new FileOutputStream("[Link]");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to Bufferedoutput Concept";
byte b[]=[Link]();
[Link](b);
[Link]();
[Link]();
[Link]();
FileInputStream fin=new FileInputStream("[Link]");
BufferedInputStream bis=new BufferedInputStream(fin);
int size=[Link]();
for(int i=0;i<size;i++)
{
[Link](i);
[Link](i);
[Link]((char)[Link]());
[Link]();
}
[Link]();
[Link]();
}
}
33
3.7 Randomly Accessing A File
In java, the [Link] package has a built-in class RandomAccessFile that enables a file to be accessed
randomly. The RandomAccessFile class has several methods used to move the cursor position in a file.
A random access file behaves like a large array of bytes stored in a file.
Access Modes
Using the RandomAccessFile, a file may created in the following modes.
• r - Creates the file with read mode; Calling write methods will result in an IOException.
• rw - Creates the file with read and write mode.
• rwd - Creates the file with read and write mode - synchronously. All updates to file
content is written to the disk synchronously.
• rws - Creates the file with read and write mode - synchronously. All updates to file
content or meta data is written to the disk synchronously.
Methods Description
void close () Closes this random access fi le stream.
long getFilePointer() Returns the current offset in this fi le.
long length () Returns the length of the fi le.
int read () Reads a byte of data from this fi le.
int read (byte [] b) Reads up to [Link] bytes of data from this fi le into an array
of bytes.
int read(byte[] b, int off, int Reads up to len bytes of data from this fi le into an array of
len) bytes starting at offset off in the byte array.
final boolean readBoolean() Reads a boolean from this fi le.
byte readByte() Reads a signed eight-bit value from this fi le.
final char readChar() Reads a character from this fi le.
final double readDouble() Reads a double from this fi le.
final float readFloat() Reads a float from this fi le.
final int readlnt () Reads a signed 32-bit integer from this fi le.
final String readLine() Reads the next line of the text from this fi le.
final long readLong() Reads a signed 64-bit integer from this fi le.
final short readShort() Reads a signed 16-bit number from this fi le.
void seek(long pos) Sets the fi le-pointer, measured from the beginning of this
file, at which the next read or write operation occurs.
34
final void write(int b) Writes the specified byte to this fi le.
final void Writes a boolean to the file as a one-byte value.
writeBoolean(boolean v)
final void writeByte(int v) Writes a byte to the fi le as a one-byte value.
final void writeBytes(String s) Writes the string to the fi le as a sequence of bytes.
final void writeChar(int v) Writes char to the fi le as a two-byte value, high byte first.
final void writeChars(String s) Writes string to the fi le as a sequence of characters
final void writelnt(int v) Writes an int to the file as four bytes, high byte first.
final void writeLong(long v) Writes a long to the file as eight bytes, high byte first.
final void writeShort(int v) Writes a short to the file as two bytes, high byte first.
Example Program :
import [Link].*;
class RandomFile
{
public static void main(String args[])throws IOException
{
RandomAccessFile fr=new RandomAccessFile("[Link]","rw");
String s="Welcome to Random Access file";
[Link]([Link]());
[Link](8);
int i=[Link]();
while(i!=-1)
{
[Link]((char)i);
i=[Link]();
}
}
}
35
Unit-III Questions
1. Explain Exception Handling in detail.
2. Explain thread in detail./ Mutithreading
3. Thread life cycle
4. Exception and Exception handling Techniques
5. Explain about user defined exception
6. Thread priorities
7. [Link] package / streams
8. Scanner class and Randomaccessfile
9. Synchronization
36