Exception in Java
Exception in Java
Sample Code
The basic syntax to handle an Exception looks like this:
String myException()
{
try
{
return myMethod();
}
catch ( IOException e )
{
return null;
}
}
There are three types of Exceptions:
3.
4. Error - The errors in java are external to the application. These
are the exceptional conditions that could not be usually anticipated by
the application and also could not be recovered from. Error exceptions
belong to Error and its subclasses are not subject to the catch or
Specify requirement. Suppose a file is successfully opened by an
application for input but due to some system malfunction could not be
able to read that file then thejava.io.IOError would be thrown. This
error will cause the program to terminate but if an application wants
then the error might be caught. An Error indicates serious problems
that a reasonable application should not try to catch. Most such errors
are abnormal conditions.
Hence we conclude that Errors and runtime exceptions are together
called as unchecked exceptions.
Exception Classes
It is clear from the above program that there is something abnormal with the
speed of the car i.e. either it is very fast or it is very slow. Hence two
exceptions are thrown by the program
-VeryFastException and VerySlowException. To be more precise
the SpeedException family specifies three new exceptions thrown by the
program which indicate some abnormal conditions. That is the
SpeedException specifies that there is something unusual with the speed;
VeryFastException and VerySlowException specifies the abnormal
conditions of the speed.
NOTE: The SpeedException extends Exception only and not the Throwable
or Error class.
Lets have a look at the example which shows the implementation of the try,
catch and finally block. Here we have used "fis = new FileInputStream (new
File (args[0]));" which throws an exception if we write a name of a file which
doesn't exist as shown in the output.
import java.io.*;
class Test{
public static void main(String args[])throws
IOException {
FileInputStream fis=null;
try{
fis = new FileInputStream (new File (args[0]));
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
finally{
fis.close();
}
}
}
Output of program:
C:\Roseindia\vinod\Exception>javac
Test.java
C:\Roseindia\vinod\Exception>java
Test
File not found!
import java.io.*;
class Test{
public static void main(String args[]){
FileInputStream fis=null;
try {
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
catch (IOException e){
System.out.println("Unable to read file!");
}
finally{
System.out.println();
System.out.println("In finally.");
try{
if(fis!=null){
fis.close();
}
}
catch (IOException ioe){
System.out.println("In finally.");
}
}
}
}
Output of program:
C:\Roseindia\vinod\Exception>javac
Test.java
C:\Roseindia\vinod\Exception>java
Test abc
File not found!
In finally.
import java.io.*;
class Test3{
public static void main(String args[]) throws FileNotFoundException,IOException {
FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
int ch;
while ((ch = fis.read()) != -1){
System.out.print ((char) ch);
}
fis.close();
}
}
Output of program:
C:\Roseindia\vinod\Exception>javac Test3.java
C:\Roseindia\vinod\Exception>java Test3
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at Test3.main(Test3.java:6)
Output of program:
C:\Roseindia\vinod\Exception>javac
Test.java
C:\Roseindia\vinod\Exception>java
Test
MyException: can't be divided by
zero
at Test.divide(Test.java:10)
at Test.main(Test.java:15)
C:\Roseindia\vinod\Exception>
So far we have seen how to use a single catch block, now we will see how to
use more than one catch blocks in a single try block.In java when we handle
the exceptions then we can have multiple catch blocks for a particular try
block to handle many different kind of exceptions that may be generated
while running the program i.e. you can use more than one catch clause in a
single try block however every catch block can handle only one type of
exception. this mechanism is necessary when the try block has statement that
raise different type of exceptions.
The syntax for using this clause is given below:-
try{
………
………
}
catch(<exceptionclass_1> <obj1>){
//statements to handle the exception
}
catch(<exceptionclass_2> <obj2>){
//statements to handle the exception
}
catch(<exceptionclass_N> <objN>){
//statements to handle the exception
}
try
{
res = num1/num2;
System.out.println("The result is" +res);
}
catch
(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error…. Array is
out of Bounds");
}
catch (ArithmeticException e)
{
System.out.println ("Can't be divided
by Zero");
}
}
}
try
{
res = num1/num2;
System.out.println("The result is"
+res);
}
catch
(ArrayIndexOutOfBoundsException e)
{
System.out.println("Assigning the
array beyond the upper bound");
}
catch (ArithmeticException e)
{
System.out.println ("Can't be
divided by Zero");
}
}
}
C:\Roseindia\>javac
Multi_Catch.java
C:\Roseindia\>java
Multi_Catch
Assigning the array beyond
the upper bound
C:\Roseindia\>javac Generic_Excep.java
C:\Roseindia\>java Generic_Excep
Error....java.lang.StringIndexOutOfBoundsException:String
index out of range: 9
In this example we didn't specify that which one exception may occur during
the execution of program but here we are trying to access the value of an
array that is out of bound still we don't need to worry about handle the
exception because we have used the Exception class that is responsible to
handle any type of exception.
In Java we can have nested try and catchblocks. It means that, a try statement can
be inside the block of another try. If an inner try statement does not have a
matching catch statement for a particular exception, the control is transferred
to the next try statement’s catch handlers that are expected for a matching
catch statement. This continues until one of the catch statements succeeds, or
until all of the nested try statements are done in. If no one catch statements
match, then the Java run-time system will handle the exception.
The syntax of nested try-catch blocks is given below:
try {
try {
// ...
}
catch (Exception1 e)
{
//statements to handle
the exception
}
}
catch (Exception 2 e2)
{
//statements to handle
the exception
}
import java.io.*;
public class NestedTry{
public static void main (String args[])throws IOException {
int num=2,res=0;
try{
FileInputStream fis=null;
fis = new FileInputStream (new File (args[0]));
try{
res=num/0;
System.out.println("The result is"+res);
}
catch(ArithmeticException e){
System.out.println("divided by Zero");
}
}
catch (FileNotFoundException e){
System.out.println("File not found!");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index is Out of bound! Argument required");
}
catch(Exception e){
System.out.println("Error.."+e);
}
}
}
If the outer try block's statements run successfully then the inner
try will raise an ArithmeticException as:
C:\Roseindia\>javac
NestedTry.java
C:\Roseindia\>java NestedTry
student.txt
divided by Zero
• your code can simply throw the custom exception when something goes
wrong.
• You can wrap an exception that provides extra information by adding
your own message.
Lets see an example that has the implementation of User Define Exception:
import java.io.*;
import java.util.*;
class MyException extends Exception
{
private String nm="";
public String getMessage(String s)
{
nm=s;
return ("you are not permitted to enter
inside "+nm);
}
}
In this example we have created own exception class as MyException that throws
an exception and a function with argument as getMessage that shows an
exception message, if the user tries to enter the another name which doesn't
match with a particular predefined name. After throwing exception the
control will be transferred in the catch block to handle the exception where
the function is invoked to display the message included in that function.
Manually generated Exceptions - These are the exceptions which are being
generated manually by your code and by which some of the error
conditions are reported to the caller of a method .
Instead of this this method you can get more information about the error
process if you print astack trace from the exception using
the printStackTrace() method that is the method of theThrowable class and
prints the stack trace to the console and provides the line numbers of
statements that called the methods in the current stack.
Lets see an example that prints an exception's message.
Exceptions:
Exception, that means exceptional errors. Actually exceptions are used for
handling errors in programs that occurs during the program execution.
During the program execution if any error occurs and you want to print your
own message or the system message about the error then you write the part of
the program which generate the error in the try{} block and catch the errors
using catch() block. Exception turns the direction of normal flow of the
program control and send to the related catch() block. Error that occurs
during the program execution generate a specific object which has the
information about the errors occurred in the program.
In the following example code you will see that how the exception handling
can be done in java program. This example reads two integer numbers for the
variables a and b. If you enter any other character except number ( 0 - 9 )
then the error is caught by NumberFormatException object. After
that ex.getMessage() prints the information about the error occurring causes.
Code of the program :
import java.io.*;
C:\vinod\xml>java
exceptionHandle
1. Checked Exceptions
2. The error
3. Runtime exception
Introduction
The Java I/O means Java Input/Output and is a part of java.io package. This
package has a InputStreamand OutputStream. Java InputStream is for
reading the stream, byte stream and array of byte stream. It can be used for
memory allocation. TheOutputStream is used for writing byte and array of
bytes. Here, you will know several interfaces provided by the java.io package
as follows:
Interfaces and Descriptions:
DataInput This interface can be used for reading byte
stream and reconstructing the java primitive
data types.
DataOutput This interface can be used for writing the
byte stream and converting data from the java
primitive data types.
Externalizable This is written in Serializable Stream. It save
and store it's contents.
FileFilter It can be used for Filtering the Pathnames.
FilenameFilter This interface used for Filter the Filenames.
ObjectInput This interface used for reading of objects and
it extends the DataInput interface.
ObjectInputValidation This is a Callback interface. It allows the
validation of objects within a graph.
ObjectOutput This interface used for writing of objects and
it extends the DataOutput interface.
ObjectStreamConstants This interface used for Constants writing into
Serialization Objects Stream.
Serializable This interface implementing in the
java.io.Serializable interface.
Filter Files in Java: The Filter File Java example code provides the
following functionalities:
• Filtering the files depending on the file extension provided by the user
• User provides the file extension and then program lists all the matching
files found
Program accepts directory name and file extension from user and displays the
files present in the directory.
Program begins with import statement java.io.*; package, which is required
for any input/output operations.
Classes Defined in the program:
OnlyExt
The constructor of the class takes file extension as parameter and then prefix
it with "*." and assign into the global variable ext. The OnlyExt class
implements FilenameFilter interface, so we have to implement the abstract
method accept() defined in the FilenameFilter interface. The accept() method
tests if a specified file should be included in a file list.
FilterFiles:
The FilterFiles contains
the public static void main(String args[]), which is the entry point of
our program. The program first accepts directory name and file extension
from the user and creates the object of OnlyExt class passing file extension
as constructor parameter.
Here is the code of the program :
import java.io.*;
Java read file line by line: In the section you will learn how to write java
program to read file line by line. We will use the DataInputStream class to
Read text File Line by Line.
Class DataInputStream
A data input stream is use to read primitive Java data types from an
underlying input stream in a machine-independent way. An application uses
a data output stream to write data that can later be read by a data input
stream.
Data input streams and data output streams represent Unicode strings in a
format that is a slight modification of UTF-8. (For more information, see
X/Open Company Ltd., "File System Safe UCS Transformation Format
(FSS_UTF)", X/Open Preliminary Specification, Document Number: P316.
This information also appears in ISO/IEC 10646, Annex P.) Note that in the
following tables, the most significant bit appears in the far left-hand column.
BufferedReader
Read text from a character-input stream, buffering characters so as to provide
for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default
is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding read
request to be made of the underlying character or byte stream. It is therefore
advisable to wrap a BufferedReader around any Reader whose read()
operations may be costly, such as FileReaders and InputStreamReaders. For
example,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation
of read() or readLine() could cause bytes to be read from the file, converted
into characters, and then returned, which can be very inefficient.
Programs that use DataInputStreams for textual input can be localized by
replacing each DataInputStream with an appropriate BufferedReader.
Here is the code of java program to Read text File Line by Line:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Create File in Java: Whenever there need to be store data, you have to
create a file into some directory. In this program, we will see how to create a
file. This example takes the file name and text data for adding into the file.
For creating a new file File.createNewFile() method has been used. This
method returns a boolean value true if the file is created otherwise return
false. If the mentioned file for the specified directory is already exist then
the createNewFile() method returns the false otherwise the method creates
the mentioned file and return true. The constructor of the FileWriter class
takes the file name which has to be buffered by theBufferedWriter stream.
The write() method of BufferedWriter class is used to create the file into
specified directory.
Following code write data into new file:
out.write(read_the_Buffered_file_name);
Following code creates the object of FileWriter and BufferedWriter:
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
Copying one file to another: This example illustrates how to copy contents
from one file to another file. This topic is related to the I/O (input/output)
of java.io package.
In this example we are using File class of java.io package. The File class is
an abstract representation of file and directory pathnames. This class is an
abstract, system-independent view of hierarchical pathnames. Anabstract
pathname has two components:
Explanation
This program copies one file to another file. We will be declaring a function
called copyfile which copies the contents from one specified file to another
specified file.
copyfile(String srFile, String dtFile)
The function copyfile(String srFile, String dtFile) takes both file name as
parameter. The function creates a new File instance for the file name passed
as parameter
File f1 = new File(srFile);
File f2 = new File(dtFile);
and creates another InputStream instance for the input object and
OutputStream instance for the output object passed as parameter
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
and then create a byte type buffer for buffering the contents of one file and
write to another specified file from the first one specified file.
// For creating a byte type buffer
byte[] buf = new byte[1024];
// For writing to another specified file from buffer buf
out.write(buf, 0, len);
Code of the Program :
import java.io.*;