Exception Handling in Java
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.
What is Exception in Java
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the
normal flow of the program. It is an object which is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Types of Java Exceptions
There are mainly two types of exceptions: checked and
unchecked. Here, an error is considered as the unchecked exception. According
to Oracle, there are three types of exceptions:
1.Checked Exception
2.Unchecked Exception
3.Error
Difference between Checked and Unchecked Exceptions
1)Checked Exception
The classes which directly inherit Throwable class
except RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at compile-time.
2)Unchecked Exception
The classes which inherit RuntimeException are known
as unchecked exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3)Error
Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords
There
are 5 keywords which are used in handling exceptions in Java.
try:-The
"try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.
catch:-The
"catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed by
finally block later.
finally:-The
"finally" block is used to execute the important code of the program.
It is executed whether an exception is handled or not.
throw:-The
"throw" keyword is used to throw an exception.
throws:-The
"throws" keyword is used to declare exceptions. It doesn't throw an
exception. It specifies that there may occur an exception in the method. It is
always used with method signature.
Java Exception Handling Example
Let's see an example of Java
Exception Handling where we using a try-catch statement to handle the
exception.
public class JavaExceptionExample
{
public static void main(String
args[])
{
try
{
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the
code...");
}
}
Java try block
Java try block is used to enclose
the code that might throw an exception. It must be used within the method.
If an exception occurs at the
particular statement of try block, the rest of the block code will not execute.
So, it is recommended not to keeping the code in try block that will not throw
an exception.
Java try block must be followed by
either catch or finally block.
syntax of Java try-catch
try
{
//code that may throw an
exception
}
catch(Exception_class_Name ref)
{}
Syntax of try-finally block
try
{
//code that may throw an
exception
}
finally
{}
Java catch block
Java catch block is used to handle
the Exception by declaring the type of exception within the parameter. The
declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the
generated type of exception.
The catch block must be used after
the try block only. You can use multiple catch block with a single try block.
public class TryCatchExample2
{
public static void main(String[]
args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the
code");
}
}
Compile by: javac
TryCatchExample2.java
Run by: java TryCatchExample2
java.lang.ArithmeticException: / by
zero
rest of the code
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.
Points to remember
oAt a time only one exception occurs and at a time only one catch block is executed.
oAll catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
public class MultipleCatchBlock
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Compile by: javac MultipleCatchBlock1.java
Run by: java MultipleCatchBlock1
Arithmetic Exception occurs
rest of the code
Java Nested try block
The try block within a try block is known as nested try block in java.
Why use nested try block
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.
Syntax:
1. ....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
class Excep6
{
public static void main(String args[]){
try
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.
java throw keyword example
In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Java 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.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.
Syntax of java throws
1.return_type method_name() throws exception_class_name
{
2.//method code
3.}
Which exception should be declared
Ans) checked exception only, because:
ounchecked Exception: under your control so correct your code.
oerror: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
import
java.io.*;
class M
{
void method()throws IOException
{
throw new IOException("device
error");
}
}
class
Testthrows4
{
public
static void main(String args[])throws IOException
{//declare
exception
M m=new
M();
m.method();
System.out.println("normal
flow...");
}
}
Output:Runtime
Exception
There are
many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
throw
|
throws
|
Java throw keyword is used to explicitly throw an
exception.
|
Java throws keyword is used to declare an exception.
|
Checked exception cannot be propagated using throw only.
|
Checked exception can be propagated with throws.
|
Throw is followed by an instance.
|
Throws is followed by class.
|
Throw is used within the method.
|
Throws is used with the method signature.
|
You cannot throw multiple exceptions.
|
You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException. |
Java 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 exception is handled or not.
Java finally
block follows try or catch block.
Why use java
finally
oFinally
block in java can be used to put "cleanup" code such as closing a
file, closing connection etc.
class
TestFinallyBlock
{
public static void main(String args[])
{
try
{
int
data=25/5;
System.out.println(data);
}
catch(NullPointerException
e)
{
System.out.println(e);
}
Finally
{
System.out.println("finally
block is always executed");}
}
Output:5
finally block is always executed
rest of the code...
Difference between final, finally
and finalize
There are
many differences between final, finally and finalize. A list of differences
between final, finally and finalize are given below:
final
|
finally
|
finalize
|
Final is used to apply restrictions on class, method and
variable. Final class can't be inherited, final method can't be overridden
and final variable value can't be changed.
|
Finally is used to place important code, it will be
executed whether exception is handled or not.
|
Finalize is used to perform clean up processing just
before object is garbage collected.
|
Final is a keyword.
|
Finally is a block.
|
Finalize is a method.
|
Java final
example
class
FinalExample{
public
static void main(String[] args)
{
final int
x=100;
x=200;//Compile
Time Error
}
}
Java
finally example
class
FinallyExample
{
public
static void main(String[] args)
{
try
{
int
x=300;
}
catch(Exception
e)
{
System.out.println(e);
}
finally
{
System.out.println("finally
block is executed");
}
}}
Java
finalize example
class
FinalizeExample
{
public
void finalize()
{
System.out.println("finalize
called");
}
public
static void main(String[] args)
{
FinalizeExample
f1=new FinalizeExample();
FinalizeExample
f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}
}
Some
important Byte stream classes.
These classes define several key methods. Two most
important are
1.read() : reads byte of data.
2.write() : Writes byte of data.
Java Character Stream Classes
Character stream is also defined by using two abstract
class at the top of hierarchy, they are Reader and Writer.
These two abstract classes have several concrete classes
that handle unicode character.
Some important Charcter stream classes
Useful methods of OutputStream
InputStream
class
Useful
methods of InputStream
Java User Defined Exception
import java.util.Scanner;
class OddNumberException extends
Exception // Statement 1
{
OddNumberException()
{
super("Odd number
exception");
}
OddNumberException(String msg)
{
super(msg);
}
}
class UserdefinedExceptionDemo
{
public static void main(String[]
args)
{
int num;
Scanner Sc = new
Scanner(System.in);
System.out.print("\n\tEnter
any number : ");
num =
Integer.parseInt(Sc.nextLine());
try
{
if(num%2 != 0)
throw(new
OddNumberException()); // Statement 2
else
System.out.print("\n\t"
+ num + " is an even number");
}
catch(OddNumberException Ex)
{
System.out.print("\n\tError :
" + Ex.getMessage());
}
System.out.print("\n\tEnd of
program");
}
}
Output:
Enter any number : 47
Error : Odd number exception
End of program
Java IO
Stream
Java
performs I/O through Streams. A Stream is linked to a physical layer by java
I/O system to make input and output operation in java. In general, a stream
means continuous flow of data. Streams are clean way to deal with input/output
without having every part of your code understand the physical.
Java
encapsulates Stream under java.io package. Java defines two types of streams.
They are,
1.Byte
Stream : It provides a convenient means for handling input and output of byte.
2.Character
Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be
internationalized.
Java Byte
Stream Classes
Byte stream
is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.
These two
abstract classes have several concrete classes that handle various devices such
as disk files, network connection etc.
Some
important Byte stream classes.
Stream class
|
Description
|
BufferedInputStream
|
Used for Buffered
Input Stream.
|
BufferedOutputStream
|
Used for
Buffered Output Stream.
|
DataInputStream
|
Contains
method for reading java standard datatype
|
DataOutputStream
|
An output
stream that contain method for writing java standard data type
|
FileInputStream
|
Input stream
that reads from a file
|
FileOutputStream
|
Output stream
that write to a file.
|
InputStream
|
Abstract class
that describe stream input.
|
OutputStream
|
Abstract class
that describe stream output.
|
PrintStream
|
Output Stream
that contain
print() and println() method |
These classes define several key methods. Two most
important are
1.read() : reads byte of data.
2.write() : Writes byte of data.
Java Character Stream Classes
Character stream is also defined by using two abstract
class at the top of hierarchy, they are Reader and Writer.
These two abstract classes have several concrete classes
that handle unicode character.
Some important Charcter stream classes
Stream class
|
Description
|
BufferedReader
|
Handles
buffered input stream.
|
BufferedWriter
|
Handles buffered
output stream.
|
FileReader
|
Input stream
that reads from file.
|
FileWriter
|
Output stream
that writes to file.
|
InputStreamReader
|
Input stream
that translate byte to character
|
OutputStreamReader
|
Output stream
that translate character to byte.
|
PrintWriter
|
Output Stream
that contain
print() and println() method. |
Reader
|
Abstract class
that define character stream input
|
Writer
|
Abstract class
that define character stream output
|
Reading
Console Input
We use the
object of BufferedReader class to take inputs from the keyboard.
Reading Characters
read()
method is used with BufferedReader object to read characters. As this function
returns integer type value has we need to use typecasting to convert it into
char type.
class
CharRead
{
public
static void main( String args[])
{
BufferedReader
br = new Bufferedreader(new InputstreamReader(System.in));
char c =
(char)br.read(); //Reading character
}
}
Reading Strings in Java
To read
string we have to use readLine() function with BufferedReader class's object.
import
java.io.*;
class
MyInput
{
public
static void main(String[] args)
{
String text;
InputStreamReader
isr = new InputStreamReader(System.in);
BufferedReader
br = new BufferedReader(isr);
text =
br.readLine(); //Reading String
System.out.println(text);
}
}
Program to read from a file using
BufferedReader class
import java.
Io *;
class
ReadTest
{
public
static void main(String[] args)
{
try
{
File fl =
new File("d:/myfile.txt");
BufferedReader
br = new BufferedReader(new FileReader(fl)) ;
String str;
while
((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
fl.close();
}
catch(IOException
e) {
e.printStackTrace();
}
}
}
Program to write to a File using
FileWriter class
import java.
Io *;
class
WriteTest
{
public
static void main(String[] args)
{
try
{
File fl =
new File("d:/myfile.txt");
String
str="Write this string to my file";
FileWriter
fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
fl.close();
}
catch
(IOException e)
{
e.printStackTrace(); }
}
}
Java I/O (Input and Output) is used
to process the input and produce the output.
Java uses
the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
A stream is
a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3
streams are created for us automatically. All these streams are attached with
the console.
1)
System.out: standard output stream
2)
System.in: standard input stream
3)
System.err: standard error stream
OutputStream vs InputStream
The
explanation of OutputStream and InputStream classes are given below:
OutputStream
Java
application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.
InputStream
Java
application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
OutputStream class
OutputStream
class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to
some sink.
Useful methods of OutputStream
Method
|
Description
|
1) public void
write(int)throws IOException
|
is used to
write a byte to the current output stream.
|
2) public void
write(byte[])throws IOException
|
is used to
write an array of byte to the current output stream.
|
3) public void
flush()throws IOException
|
flushes the
current output stream.
|
4) public void
close()throws IOException
|
is used to
close the current output stream.
|
InputStream
class
InputStream class is an abstract class. It is the
superclass of all classes representing an input stream of bytes.
Useful
methods of InputStream
Method
|
Description
|
1) public
abstract int read()throws IOException
|
reads the next
byte of data from the input stream. It returns -1 at the end of the file.
|
2) public int
available()throws IOException
|
returns an
estimate of the number of bytes that can be read from the current input
stream.
|
3) public void
close()throws IOException
|
is used to
close the current input stream.
|
java FileInputStream
Class
Java FileInputStream
class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also
read character-stream data. But, for reading streams of characters, it is recommended
to use FileReader class.
Java FileInputStream
class declaration
Let's see the declaration
for java.io.FileInputStream class:
1.public class
FileInputStream extends InputStream
java FileInputStream class methods
Method
|
Description
|
int available()
|
It is used to return the estimated number of bytes that
can be read from the input stream.
|
int read()
|
It is used to read the byte of data from the input stream.
|
int read(byte[] b)
|
It is used to read up to b.length bytes of data from the input stream.
|
int read(byte[] b, int off, int len)
|
It is used to read up to len bytes of data from the input stream.
|
long skip(long x)
|
It is used to skip over and discards x bytes of data from
the input stream.
|
FileChannel getChannel()
|
It is used to return the unique FileChannel object
associated with the file input stream.
|
FileDescriptor getFD()
|
It is used to return the FileDescriptor object.
|
protected void finalize()
|
It is used to ensure that the close method is call when
there is no more reference to the file input stream.
|
void close()
|
It is used to closes the stream.
|
java FileInputStream example 1: read
single character
import java.io.FileInputStream;
public class DataStreamExample
{
public static void main(String
args[]){
try{
FileInputStream fin=new
FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception
e){System.out.println(e);}
}
}
OUTPUT W
Java FileInputStream example 2: read
all characters
package com.javatpoint;
import java.io.FileInputStream;
public class DataStreamExample
{
public static void main(String
args[]){
try
{
FileInputStream fin=new
FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception
e){System.out.println(e);}
}
}
Output:
Welcome to javaTpoint
Java FileOutputStream Class
Java FileOutputStream is an output
stream used for writing data to a file.
If you have to write primitive
values into a file, use FileOutputStream class. You can write byte-oriented as
well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than
FileOutputStream.
FileOutputStream class declaration
1.public class FileOutputStream
extends OutputStream
Java FileOutputStream Example 1: write byte
}
Java FileWriter Class
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly.
import java.io.FileWriter;
public class FileWriterExample
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome ");
fw.close();
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Success...");
}
}
import java.io.*;
FileOutputStream class methods
Method
|
Description
|
protected void finalize()
|
It is used to clean up the connection with the file output
stream.
|
void write(byte[] ary)
|
|
void write(byte[] ary, int off, int len)
|
It is used to write len bytes from the byte array starting at offsetoff to the file output stream.
|
void write(int b)
|
It is used to write the specified byte to the file output
stream.
|
FileChannel getChannel()
|
It is used to return the file channel object associated
with the file output stream.
|
FileDescriptor getFD()
|
It is used to return the file descriptor associated with
the stream.
|
void close()
|
It is used to closes the file output stream.
|
Java FileOutputStream Example 1: write byte
import
java.io.FileOutputStream;
public
class FileOutputStreamExample
{
public
static void main(String args[])
{
try
{
FileOutputStream
fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception
e){System.out.println(e);}
}
}
Output:
Success..
The
content of a text file testout.txt is set with the data A.
testout.txt
A
Java Reader
Java Reader is
an abstract
class for reading character streams. The only methods
that a subclass must implement are read(char[], int, int) and close(). Most
subclasses, however, will override some
of the methods to provide higher efficiency, additional functionality, or both. Some of
the implementation class are BufferedReader, CharArrayReader, FilterReader, InputStreamReader,
PipedReader, StringReader
Method
|
Description
|
close()
|
It closes the stream and releases any system
resources associated with it.
|
read()
|
It reads a single character.
|
ready()
|
It tells whether this stream is ready to be
read.
|
reset()
|
It resets the stream.
|
skip(long n)
|
It skips characters.
|
import
java.io.*;
public
class ReaderExample
{
public
static void main(String[] args)
{
try
{
Reader
reader = new FileReader("file.txt");
int data =
reader.read();
while
(data != -1)
{
System.out.print((char)
data);
data =
reader.read();
}
reader.close();
}
catch
(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
Java Writer
It is an
abstract class for writing to character streams. The methods that a subclass
must implement are write(char[], int, int), flush(), and close(). Most
subclasses will override some of the methods defined here to provide higher
efficiency, functionality or both.
Method
|
Description
|
append(char c)
|
It appends the specified character to this writer.
|
close()
|
It closes the stream, flushing it first.
|
flush()
|
It flushes the stream.
|
write(int c)
|
It writes a single character.
|
write(String str)
|
It writes a string.
|
write(String str, int off, int len)
|
It writes a portion of a string.
|
import java.io.*;
public class WriterExample
{
public static void main(String[]
args)
{
try
{
Writer w = new
FileWriter("output.txt");
String content = "I love my
country";
w.write(content);
w.close();
System.out.println("Done");
}
catch (IOException e)
{
e.printStackTrace();
}
}
java
FileReader Class
Java
FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class.It is character-oriented class which is used
for file handling in java.
Method
|
Description
|
int
read()
|
It
is used to return a character in ASCII form. It returns -1 at the end of
file.
|
void
close()
|
It
is used to close the FileReader class.
|
import
java.io.FileReader;
public
class FileReaderExample
{
public
static void main(String args[])throws Exception
{
FileReader
fr=new FileReader("D:\\testout.txt");
int
i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array because it provides method to write string directly.
Method
|
Description
|
void
write(String text)
|
It
is used to write the string into FileWriter.
|
void
write(char c)
|
It
is used to write the char into FileWriter.
|
void
write(char[] c)
|
It
is used to write char array into FileWriter.
|
void
flush()
|
It
is used to flushes the data of FileWriter.
|
void
close()
|
It
is used to close the FileWriter.
|
import java.io.FileWriter;
public class FileWriterExample
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome ");
fw.close();
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Success...");
}
}
Java File Class
The File class is an abstract representation of file and directory
pathname. A pathname can be either absolute or relative.
The File class have several methods for working with directories and
files such as creating new directories or files, deleting and renaming
directories or files, listing the contents of a directory etc.
Method
|
Description
|
createNewFile()
|
It
atomically creates a new, empty file named by this abstract pathname if and
only if a file with this name does not yet exist.
|
canWrite()
|
It
tests whether the application can modify the file denoted by this abstract
pathname.String[]
|
canExecute()
|
It
tests whether the application can execute the file denoted by this abstract
pathname.
|
canRead()
|
It
tests whether the application can read the file denoted by this abstract
pathname.
|
isAbsolute()
|
It
tests whether this abstract pathname is absolute.
|
isDirectory()
|
It
tests whether the file denoted by this abstract pathname is a directory.
|
isFile()
|
It
tests whether the file denoted by this abstract pathname is a normal file.
|
import java.io.*;
public class FileDemo
{
public static void main(String[] args
{
try
{
File file = new File("javaFile123.txt");
if (file.createNewFile())
{
System.out.println("New File is
created!");
}
else
{
System.out.println("File already
exists.");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}