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 keywordtry is used to define a block of code that will be tests the occurence of an
exception.
2
The keywordcatchis used to define a block of code that handles the exception occurred in
the respective try block..
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");
}
}
}
3
when an exception occurs in the try block the execution control transferred to the catch
block and the catch block handles it.
catch(ArrayIndexOutOfBoundsExceptionaie)
{
[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.
thrownew ThrowableInstance;
Example:
class Test
{
static void check(int age)
{
if(age<18)
throw new ArithmeticException("Not Elgible to Vote");
else
[Link]("Elgible to Vote");
}
import [Link].*;
class throwsException
{
public static void main(String args[]) throws FileNotFoundException
{
FileReaderfr=new FileReader(" [Link]");
}
}
throwskeyword will not handle the error, it’s convinced the compiler and avoids the
abnormal termination of a program.
1.2.5finally keyword
The finally keyword used to define a block that must be executed irrespective of exception
occurrence.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
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");
}
7
finally
{
[Link]("Java Finally Block");
}
}
}
1.2.6Rethrowing Exception
class rethrow
{
public static void main(String args[])
{
try
{
[Link](10/0);
}
catch(ArithmeticException ae)
{
throw new NumberFormatException();
}
}
}
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.2Creating 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 NewThreadimplements 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:
13
{
[Link]("i = " + i);
}
} }
class ThreadTest
{
public static void main(String[] args)
{
SampleThread th = new SampleThread();
Thread obj = new Thread(th);
[Link]("Thread about to start...");
[Link]();
}
}
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
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).
15
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 ofthese methods:[Link](), [Link](), and
[Link]()
(all these methods should be called withtime out specified).
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
Tells to the scheduler that the current thread is willing
yield( ) void
to yield its current use of a processor.
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
}
}
[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)
{
18
}
[Link]("Thread2 Running");
[Link]();
}
}
19
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] contains two top level byte stream abstract
classes:[Link] (for reading bytes)and [Link](for
writing bytes).
The [Link] also contains two other level character stream abstract classes:
[Link] (for reading characters)and [Link](for writing characters).
20
The
booleancreateNewFile() It returns true if the named file does not exist and was
successfully created; false if the named file already
exists.
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]());
}
}
22
& 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
Example:-
import [Link].*;
class Inputstream
{
public static void main(String args[])throws IOException
{
byte b[] = new byte[100];
FileInputStream f1= new FileInputStream("D:\\[Link]");
[Link]("Available bytes in the file: " +
[Link]());
[Link](b);
[Link]("Data read from the file: ");
// Convert byte array into string
String data = new String(b);
[Link](data);
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[] b) It writes a whole byte array(b) to the output
stream.
void write(byte[] b, Writes m bytes from array b starting from nth
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.
import [Link].*;
class FileOutputStreamEx
{
public static void main(String args[])throws IOException
{
FileOutputStreamfout=new FileOutputStream("[Link]");
String s="Welcome to Java io";
byte b[]=[Link]();
[Link](b);
[Link]();
[Link]();
[Link]("Success");
}
}
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.
25
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
booleanhasNext()
another token else false.
Returns true if the next token matches
booleanhasNext(Pattern p)
the specified pattern (p).
Returns true if the next token matches
booleanhasNext(String p) the pattern in the specified string
(p).
Returns true if the next token in this
booleanhasNextBoolean() input can be interpreted as a Boolean
value
Returns true if the next token in this
booleanhasNextByte() input can be interpreted as a byte
value.
Returns true if the next token in this
booleanhasNextDouble() input can be interpreted as a double
value.
Returns true if the next token in this
booleanhasNextFloat()
input can be interpreted as a fl oat.
Returns true if the next token in this
booleanhasNextInt()
input can be interpreted as an int.
Returns true if there is another line
booleanhasNextLine()
in the input.
Returns true if the next token in this
booleanhasNextLong() scanner’s input can be interpreted as a
long
Returns true if the next token in this
booleanhasNextShort() scanner’s input can be interpreted as a
short.
26
Returns the next complete token from
String next()
this scanner.
Returns the next token if it matches
String next(Patternpattern)
the specified pattern.
Scans the next token of the input into
booleannextBoolean()
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
(Stringpattern)
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);
[Link]("Entered Integer Number is "+ num);
[Link]("Entered Float Number is "+ real);
27
}
}
28
3.6 BufferedInputStream Class
BufferedInputStream class s used for buffering the input and it supports operations to re-read
the files. It extends the functionality of FileInputStream.
BufferedInputStream class is used to provide buffering to InputStream. Instead of reading
one byte at a time, it can read a large block of data. It improves reading performance.
Methods Description
int available() Returns the number of bytes that can be read from
this input stream without blocking
Void close() Closes this input stream and releases all the
resources.
Void mark(int Similar to mark the methods of InputStream.
readlimit)
booleanmarkSupported() Tests if this input stream supports the mark and
reset methods.
int read() Similar to read of InputStreamclass.
int read(byte b[],int Reads bytes from the inputStreaminto the byte array
off, int len) starting at offset off and returns
the number of bytes read. Len specifi es the
maximum number of bytes to read.
void reset() Similar to reset method of InputStreamclass.
Long skip(long n) Similar to skip method of InputStreamclass.
Example Program :
import [Link].*;
class BufferedInputStreamEx
{
public static void main(String args[])throws IOException
{
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]();
29
[Link]();
}
}
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.
final FileChannelgetChannel() Returns the unique FileChannel object associated with this fi
le.
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 booleanreadBoolean() 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.
30
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 fi
le, at
which the next read or write operation occurs.
void setLength (long Sets the length of this fi le.
newLength)
int skipBytes(int n) Skips n bytes of input discarding skipped bytes.
final void write (byte [] b) Writes [Link] bytes from the specifi ed byte array to this fi
le, starting
at the current fi le pointer.
fi nal void write (byte [] b, int Writes len bytes from the specifi ed byte array starting at
off, offset off
to this fi le.
int len)
final void write(int b) Writes the specifi ed byte to this fi le.
final void Writes a boolean to the fi le 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 fi rst.
final void writeChars(String s) Writes string to the fi le as a sequence of characters
final void Converts the double argument to a long using the
writeDouble(double v) doubleToLongBits
method in class Double, and then writes that long value to
the fi le as
an eight-byte quantity, high byte fi rst.
final void writeFloat (fl oat v) Converts the fl oat argument to an int using the floatTolntBits
method in class Float, and then writes that int value to the fi
le as a
four-byte quantity, high byte fi rst.
final void writelnt(int v) Writes an int to the fi le as four bytes, high byte fi rst.
final void writeLong(long v) Writes a long to the fi le as eight bytes, high byte fi rst.
final void writeShort(int v) Writes a short to the fi le as two bytes, high byte fi rst.
Example Program :
import [Link].*;
class RandomAccessFileDemo
{
public static void main(String args[]) throws IOException
{
31
[Link]("Opening the file in read write mode");
RandomAccessFileraf = new RandomAccessFile ("[Link]","rw");
[Link]([Link]());
String str = "\nContents appended using RandomAccessFile";
[Link]("Appending contents to file");
[Link]([Link]());
[Link]("Contents appended");
[Link]("Reading the contents of the fi le....");
[Link](0);
while((str = [Link]())!= null)
[Link](str);
[Link]();
}
}
32