Você está na página 1de 42

Exception in Java

Exception are such anomalous conditions (or typically an event) which


changes the normal flow of execution of a program. Exceptions are used for
signaling erroneous (exceptional) conditions which occur during the run time
processing. Exceptions may occur in any programming language.
Occurrence of any kind of exception in java applications may result in an
abrupt termination of the JVM or simply the JVM crashes which leaves the
user unaware of the causes of such anomalous conditions. However Java
provides mechanisms to handle such situations through its superb exception
handling mechanism. The Java programming language usesException
classes to handle such erroneous conditions and exceptional events.
Exception Object
In java, when any kind of abnormal conditions occurs with in a method then
the exceptions are thrown in form of Exception Object i.e. the normal
program control flow is stopped and an exception object is created to handle
that exceptional condition. The method creates an objectand hands it over to
the runtime system. Basically, all the information about the error or any
unusual condition is stored in this type of object in the form of a stack. This
object created is called an exception object the process is termed
as throwing an exception. The mechanism of handling an exception is
called catching an exception or handling an Exception or simply Exception
handling.

As we have known that after throwing an exception it is handed off to the


runtime system that finds a possible method from an ordered list of methods
to handle it. The list of this type of methods is known as the call stack
As we have already learned that, what are the exceptions. Point to be
remember here is that exceptions are not errors rather they are some
abnormal conditions that aren't necessarily errors. Therefore, the process of
detecting the exceptions and responding to them as well is known
asException handling.
Following are the advantages of Exception-handling in Java:

• Exception provides the means to separate the details of what to do when


something out of the ordinary happens from the main logic of a
program.
• One of the significance of this mechanism is that it throws an exception
whenever a calling method encounters an error providing that the calling
method takes care of that error.
• With the help of this mechanism the working code and the error-
handling code can be disintegrated. It also gives us the scope of
organizing and differentiating between different error types using a
separate block of codes. This is done with the help of try-catch blocks.
• Furthermore the errors can be propagated up the method call stack i.e.
problems occurring at the lower level in the chain can be handled by the
methods higher up the call chain .

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:

1. Checked Exceptions - These are the exceptions which occur


during the compile time of the program. The compiler checks at the
compile time that whether the program contains handlers for checked
exceptions or not. These exceptions do not
extendRuntimeException class and must be handled to avoid a
compile-time error by the programmer. These exceptions extend
the java.lang.Exception class These exceptional conditions should
be anticipated and recovered by an application. Furthermore Checked
exceptions are required to be caught. Remember that all the exceptions
are checked exceptions unless and until those indicated by Error,
RuntimeException or their subclasses.
For example if you call the readLine() method on a BufferedReader
object then theIOException may occur or if you want to build a
program that could read a file with a specific name then you would be
prompted to input a file name by the application. Then it passes the
name to the constructor for java.io.FileReader and opens the file.
However if you do not provide the name of any existing file then the
constructor throwsjava.io.FileNotFoundException which abrupt the
application to succeed. Hence this exception will be caught by a well-
written application and will also prompt to correct the file name.

Here is the list of checked exceptions.


NoSuchFieldException
InstantiationException
IllegalAccessException
ClassNotFoundException
NoSuchMethodException
CloneNotSupportedException
InterruptedException

2. Unchecked Exceptions - Unchecked exceptions are the


exceptions which occur during the runtime of the program. Unchecked
exceptions are internal to the application and extend
the java.lang.RuntimeException that is inherited
from java.lang.Exceptionclass. These exceptions cannot be
anticipated and recovered like programming bugs, such as logic errors
or improper use of an API. These type of exceptions are also
calledRuntime exceptions that are usually caused by data errors, like
arithmetic overflow, divide by zero etc.
Lets take the same file name example as described earlier. In that
example the file name is passed to the constructor for FileReader.
However, the constructor will throwNullPointerException if a logic
error causes a null to be passed to the constructor. Well in this case the
exception could be caught by the application but it would rather try to
eliminate the bug due to which the exception has occurred. You must
have encountered the most common exception in your program i.e.
the ArithmeticException. I am sure you must be familiar with the
reason of its occurrence that is when something tries to divide by zero.
Similarly when an instance data member or method of a reference
variable is to be accessed that hasn't yet referenced an object
throws NullPointerException.

Here is the list of unchecked exceptions.


IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
ClassCastException
ArithmeticException
NullPointerException
IllegalStateException
SecurityException

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

The hierarchy of exception classes commence from Throwable class which


is the base class for an entire family of exception classes, declared
in java.langpackage as java.lang.Throwable. A throwable contains a
snapshot of the execution stack at the time it was created and also a message
string that gives more information about the error. This class can be
instantiated and thrown by the program. The throwable class is further
divided into two subclasses :-

1. Exceptions - Exceptions are thrown if any kind of unusual condition


occurs that can be caught. Sometimes it also happens that the exception
could not be caught and the program may get terminated. Remember that
they are a member of Exception family and can be type
of Checked or Unchecked exception.
2. Errors - When any kind of serious problem occurs which could not be
handled easily likeOutOfMemoryError then an error is thrown. Well,
errors are not something which is thrown by you rather they are thrown
by the Java API or by the Java virtual machine itself i.e. only the
exceptions are thrown by your code and not the errors. Also Remember
that they are a member of Error family.

The exception classes can be explained as well seeing the exception


hierarchy structure:
The java.lang package defines several classes and exceptions. Some of these
classes are not checked while some other classes are checked.
EXCEPTIONS DESCRIPTION CHECKED UNCHECKED
Arithmetic errors
ArithmeticException such as a divide - YES
by zero
Arrays index is
ArrayIndexOutOfBoundsException not within - YES
array.length
Related Class not
ClassNotFoundException YES -
found
InputOuput field
IOException YES -
not found
Illegal argument
IllegalArgumentException when calling a - YES
method
One thread has
InterruptedException been interrupted YES -
by another thread
Nonexistent
NoSuchMethodException YES -
method
Invalid use of
NullPointerException - YES
null reference
Invalid string for
NumberFormatException conversion to - YES
number
As you have come to know that exceptions are Objects that means an object
is thrown when you throw an exception. Moreover only those objects could
be thrown whose classes are derived from Throwable.
It is interesting to note here that the objects of your own design could also be
thrown provided that they should be the subclass of some member of the
Throwable family. Also the throwable classes which are defined by you must
extend Exception class.
It depends upon the situation that whether to use an existing exception class
from java.lang or create any of your own. Such
as IllegalArgumentException, a subclass of RuntimeExceptionin java.lang
can be thrown if any method with an invalid argument is thrown by you. On
the other hand you need not to worry if you wish to impart some more
information about any unusual condition other than a class from java.lang
because it will be indicated by the class of exception object itself.
For example, if a thrown exception object has class
IllegalArgumentException, that indicates someone passed an illegal
argument to a method. Sometimes you will want to indicate that a method
encountered an abnormal condition that isn't represented by a class in the
Throwable family of java.lang.
For instance, lets tweak an example below that demonstrates the exceptional
conditions that might occur while driving a car.
// In Source Packet in file
except/ex1/SpeedException.java
class SpeedException extends Exception {
}
// In Source Packet in file
except/ex1/VeryFastException.java
class VeryFastException extends
SpeedException {
}
// In Source Packet in file
except/ex1/VerySlowException.java
class VerySlowException extends
SpeedException {
}
Lets tweak the diagram below.

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.

Java Catching and Handling Exceptions

The various keywords for handling exceptions are below.


• try
• catch
• finally
• throw
• throws
The three exception handler components are used to catch and handle the
exceptions. These are try, catch and finally clause. The mechanism to catch
an exception in Java is to use try and catch block. Every catch block can
handle only one type of exception however you can use more than one catch
clause in a single try block. Simply a statement is surrounded by the try block
that may cause the exception to occur. Then the try block is followed by the
catch block. And if the exception occurs then this catch block specifies a
code that should be executed.
Using try and catch:-
The syntax for the usage of try, catch and finally block is given below.
try{
………
………
}
catch(<exceptionclass1> <obj1>){
………
………
}
finally{
………
………
}
For using an exception handler in an application, the first step we need to do
is to enclose the code that is likely to generate an exception inside
a try block. If an exception occurs in the try block then it is handled by the
exception handler associated with it. For doing this we need to have one or
more catch blocks after the try block, where each catch block acts as an
exception handler and can handle the type of exception indicated by its
arguments.

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!

Download this example


The code which is to be executed in a try block indicates that it will throw an
exception. And if the exception occurs then the runtime system checks
whether the exception thrown by try block matches to the one in catch clause
or not. If yes, then the code within the catch clause gets executed which
actually handles the exception.
Using final: It is always a good practice to use finally clause after the try and
catch block because the finally block always executes even if an unexpected
exception occurs i.e. whether or not an exception thrown. The finally block
executes if and only if the try block exits. Other than exception handling the
finally clause helps you in avoiding any cleanup code accidentally bypassed
by a return etc. The statements within the finally block gets executed by the
the runtime system without taking care of what happens within the try
block.
There are two steps to use the finally clause:
• First, you need to enclose the code in a try block that has
multiple exit points.
• Secondly after the try block exits place the code that must be
executed in a finally clause.
Same way we have used the finally block which will execute after the try and
catch block.

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.

Download this example


Using throws: The other way to handle an exception is using the throws
clause. When you call a method from the java API that throws
a checked exception, you must either throw the exception or catch it. If you
decide that you can't handle the exception properly, then the exception can be
declared to the method header using the throws keyword followed by the
class name of the exception.
You might have come across the throws IOException clause in the method
header. For exampleSystem.in.read() will give a compile error for
IOException. Add the throws clause to the surrounding method to pass the
error up to the next level (or else write your own catch/try handler). This
clause is placed between the parameter list and the starting of the opening
brace of the method. We use this clause when we know that a particular
exception may occur. Then instead of terminating the program the compiler
throws the exception.
While the throw keyword (note the singular form) is used to force an
exception. It can also pass a custom message to your exception handling
module. for example:-
throw new FileNotFoundException("Could not find books.txt");
The syntax for coding the throws clause of a method is as:-
method declaration throws Exception1,[Exception2] .......{ }
Likewise we have used throws clause to the method header as "throws
FileNotFoundException,IOException " which throws an exception as shown
in the output.

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)

How to Throw Exceptions in Java

Before catching an exception it is must to be thrown first. This means that


there should be a code somewhere in the program that could catch the
exception. We use throw statement to throw an exception or simply use the
throw keyword with an object reference to throw an exception. A single
argument is required by the throw statement i.e. a throwable object. As
mentioned earlier Throwable objects are instances of any subclass of the
Throwable class.
throw new VeryFastException();
Note: The reference should be of type Throwable or one of its subclasses.
For instance the example below shows how to throw an exception. Here we
are trying to divide a number by zero so we have thrown an exception here as
"throw new MyException("can't be divided by zero");"
class MyException extends Exception {
public MyException(String msg){
super(msg);
}
}
public class Test {

static int divide(int first,int second) throws MyException{


if(second==0)
throw new MyException("can't be divided by zero");
return first/second;
}
public static void main(String[] args) {
try {
System.out.println(divide(4,0));
}
catch (MyException exc) {
exc.printStackTrace();
}
}
}

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>

Download this example


Difference between throw and throws keywords
Whenever we want to force an exception then we
use throw keyword. the throw keyword (note the singular form) is used to
force an exception. It can also pass a custom message to your exception
handling module. Moreover throw keyword can also be used to pass a
custom message to the exception handling module i.e. the message which we
want to be printed. For instance in the above example we have used -
throw new MyException ("can't be divided by zero");
Whereas when we know that a particular exception may be thrown or to pass
a possible exception then we use throws keyword. Point to note here is that
the Java compiler very well knows about the exceptions thrown by some
methods so it insists us to handle them. We can also use throws clause on
the surrounding method instead of try and catch exception handler. For
instance in the above given program we have used the following clause
which will pass the error up to the next level -
static int divide(int first,int second) throws MyException{

Handling Multiple Catch Clauses

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
}

When an exception is thrown, normal execution is suspended. The runtime


system proceeds to find a matching catch block that can handle the
exception. If no handler is found, then the exception is dealt with by the
default exception handler at the top level.

Lets see an example given below which shows the implementation of


multiple catch blocks for a single try block.

public class Multi_Catch


{
public static void main (String args[])
{
int array[]={20,10,30};
int num1=15,num2=0;
int res=0;

try
{
res = num1/num2;
System.out.println("The result is" +res);

for(int ct =2;ct >=0; ct--)


{
System.out.println("The value of array
are" +array[ct]);
}

}
catch
(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error…. Array is
out of Bounds");
}

catch (ArithmeticException e)
{
System.out.println ("Can't be divided
by Zero");
}

}
}

Output of the program:


C:\Roseindia\>javac
Multi_Catch.java
C:\Roseindia\>java
Multi_Catch
Can't be divided by Zero

In this example we have used two catch clause catching the


exceptionArrayIndexOutOfBoundsException and ArithmeticException i
n which the statements that may raise exception are kept under the try block.
When the program is executed, an exception will be raised. Now that time
the first catch block is skipped and the second catch block handles the error.
Download this program
Lets have an another output, in which the second catch block is skipped and
the first catch block handles the error.
public class Multi_Catch1
{
public static void main (String args[])
{
int array[]=new int [5];
int num1=15,num2=2;
int res=0;

try
{
res = num1/num2;
System.out.println("The result is"
+res);

for(int ct =0;ct <=5; ct++)


{
array[ct] = ct * ct ;
}

}
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");
}

}
}

Output of the program:

C:\Roseindia\>javac
Multi_Catch.java
C:\Roseindia\>java
Multi_Catch
Assigning the array beyond
the upper bound

Download this example


Handling the Unreachable Code Problem
The multiple catch blocks can generate unreachable code error i.e. if the first
catch block contains the Exception class object then the subsequent catch
blocks are never executed. This is known as Unreachable code problem.
To avoid this, the last catch block in multiple catch blocks must contain the
generic class object that is called the Exception class. This exception class
being the super class of all the exception classes and is capable of catching
any types of exception. The generic Exception class can also be used with
multiple catch blocks.
Take a look at the following example:
public class Generic_Excep
{
public static void main (String
args[])
{
String str = "Exception" ;
int len=0;
try
{
StringBuffer sbuf = new
StringBuffer(str);
len = str.length() ;
for(int ct=len;ct>=0;ct--)
{
System.out.print(sbuf.charAt(ct));
}
}
catch(Exception e)
{
System.out.println("Error...."+e);
}
}
}

Output of the program:

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.

Nested Try-Catch Blocks

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
}

Lets have an example that uses the nested try-catch blocks

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);
}
}
}

Output of the program:


C:\Roseindia\>javac NestedTry.java
C:\Roseindia\>java NestedTry
Array index is Out of bound!
Argument required

In this given example we have implemented nested try-catch blocks concept


where an inner try block is kept with in an outer try block, that's catch
handler will handle the arithmetic exception. But before that
an ArrayIndexOutOfBoundsException will be raised, if a file name is not
passed as an argument while running the program. Now lets see, what will
be the output if we pass the file name student as an argument.
C:\Roseindia\>javac
NestedTry.java
C:\Roseindia\>java NestedTry
student.txt
File not found!

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

Catching Normal Exceptions

The exceptions that are generated by methods are referred to as normal


exceptions. We have already learned that to catch an exception we use try
and catch block.
try {
myTestException();
}
catch(ExceptionType1 e) {
System.out.println(e.getMessage());
}
catch(Exceptiontype2 e) {
System.out.println(e.getMessage());
}
The code above shows how to handle multiple exceptions. We have
used myTestException();method here which generates two different types of
exceptions handled by separate catch clauses in a unique manner. By
comparing the exception type, the catch clauses are examined whenever an
exception occurs in a try block A match will occur whenever the type of
exception is same as that in catch clause or same as the subclass in the catch
clause. Hence due to this multilevel catch handlers can be provided which are
based on more derived exception types. Lets see one more example:
FileInputStream fis=null;
try{
fis = new FileInputStream (new File
(args[0]));
}
catch (FileNotFoundException e){
System.out.println("File not
found!"); + e.getMessage());
}
Here we have created a file input stream and the constructor which takes a
file name to read from will throw FileNotFoundException if the file
couldn't be found. Within a try block an object is created that handles the
exception FileNotFoundException in a catch block as the constructor is
capable of throwing this exception.
Catching Runtime Exceptions
The exceptions which are not easily traced are known as Runtime
Exceptions. For instance,
try {
int x = 50;
for (int i = 15; i >= 0; i--)
System.out.println(x / i);
}
catch(ArithmeticException e) {
System.out.println(e.getMessage());
}
The above code displays a for loop trying to divide a number by zero in its
last iteration which would result in runtime exception. We have used try
block to handle this exception and a corresponding handler by means of a
catch clause. And if we won't handle the exception the program will end up
with the termination.
The disadvantage in handling the runtime exception is that we need to put the
doubtful code inside a try block. This approach sometimes causes a mess so
its always better to avoid the problems which land you up with the troubles.

Making Custom (User Define Exceptions)


So far you would have been known, how to be handled the exceptions in java
=======
So far you would have been known, how to be handled the exceptions in java
>>>>>>> 1.3 that are thrown by the Java API but sometimes you may
occasionally need to throw your own exception i.e. if you encounter a
situation where none of those exception describe your exception accurately
or if you can't find the appropriate exception in the Java API, you can code a
class that defines an exception that is more appropriate and that mechanism
of handling exception is calledCustom or User Defined Exception.
In Java API all exception classes have two type of constructor. First is called
default constructor that doesn't accept any arguments. Another constructor
accepts a string argument that provides the additional information about the
exception. So in that way the Custom exception behaves like the rest of the
exception classes in Java API.
There are two primary use cases for a custom exception.

• 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.

The code of a Custom exception:


public class ExceptionClassName
extends Exception
{
public ExceptionClassName(){ }
public
ExceptionClassName(StringMessage
)
{
super(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);
}
}

public class ExcepDemo


{
public static void main(String args[])throws
MyException,IOException
{
String temp="";
try
{
String str="amit";
System.out.println("Enter the your
name");
BufferedReader br=new
BufferedReader(new
InputStreamReader(System.in));
temp=br.readLine();
if(!temp.equals(str))
throw new MyException();
else
System.out.println("Welcome to Rose
India");
}
catch(MyException e)
{
System.err.println(e.getMessage(temp));
}
catch(Exception e){
System.err.println(e);
}
}
}

Output of the program:


C:\Roseindia\>javac
ExcepDemo.java
C:\Roseindia\>java
ExcepDemo
Enter the your name
nisha
you are not permitted to
enter inside nisha
C:\Roseindia\>java
ExcepDemo
Enter the your name
amit
Welcome to Rose India

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.

What are Chained Exceptions in Java?

Whenever in a program the first exception causes an another exception, that


is termed as Chained Exception. Java provides new functionality for
chaining exceptions. Exception chaining (also known as "nesting exception")
is a technique for handling the exception, which occur one after another i.e.
most of the time is given by an application to response to an exception by
throwing another exception. Typically the second exception is caused by the
first exception. Therefore chained exceptions help the programmer to know
when one exception causes another.
The constructors that support chained exceptions in Throwable class are:
Throwable initCause(Throwable)
Throwable(Throwable)
Throwable(String, Throwable)
Throwable getCause()
The methods of the Throwable class are:
METHOD DESCRIPTION
Returns the exception followed by a
toString()
message string (if one exit) .
Returns the message string of the Throwable
getMessage()
object.
Returns the full name of the exception class
printStackTrace() and some additional information apart from
the information of first two method.
Returns the exception that caused the
getCause()
occurrence of current exception.
Returns the current exception due to
initCause() theThrowable constructors and
the Throwableargument to initCause.
The syntax for using a chained exception is as follows in which a new
TestException exception is created with the attached cause when
an IOException is caught. Thus the chain exception is thrown to next level
of exception handler.
try {
} catch (IOException e) {
throw new
TestException("Other
IOException", e);
}
Lets see an example having the implementation of chained exceptions:
import java.io.*;
import java.util.*;
class MyException extends Exception{
MyException(String msg){
super(msg);
}
}
public class ChainExcep{
public static void main(String
args[])throws MyException, IOException{
try{
int rs=10/0;
}
catch(Exception e){
System.err.println(e.getMessage());
System.err.println(e.getCause());
throw new MyException("Chained
ArithmeticException");
}
}
}
Output of the Program:
C:\Roseindia\>javac ChainExcep.java
C:\Roseindia\>java javac ChainExcep
/ by zero
null
Exception in thread "main"
MyException: Chained
ArithmeticException
at
ChainExcep.main(ChainExcep.java:21
)

This example has an user defined exception that throws


an ArithmeticException and has been thrown under the catch handler. After
throwing an exception, the handler will execute the statement of the catch
block and then invoke the user defined constructor. Thus the implementation
of chained exception is very helpful to the user to make a program or an
application error and exception free.
Download this example
Now lets see the two different ways to generate an Exception.

1. Exceptions generated by the Java run-time system - These are the


exceptions which violate the rules of the Java language and are related to
some fundamental errors.

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 .

How to Print a Stack Trace Message

As we have seen that java provides a method getMessage() method that is


used with an object of the Exception class to print errors to debug the
process. For example:
try {
// ......
}
catch (IOException e) {
// ...........
System.out.println("Got an
IOException: " + e.getMessage());
}

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.

public class PrintStack{


public static void main (String args[]){
String str = "Exception" ;
int len=0;
try{
StringBuffer sbuf = new StringBuffer(str);
len = str.length() ;
for(int ct=len;ct>=0;ct--){
System.out.print(sbuf.charAt(ct));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Output of the program:


C:\Roseindia\>javac PrintStack.java
C:\Roseindia\>java PrintStack
java.lang.StringIndexOutOfBoundsException:
String index out of range: 9
at java.lang.StringBuffer.charAt(Unknown
Source)
at PrintStack.main(PrintStack.java:13)

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.*;

public class exceptionHandle{


public static void main(String[] args) throws Exception{
try{
int a, b;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
a = Integer.parseInt(in.readLine());
b = Integer.parseInt(in.readLine());
}
catch (NumberFormatException ex){
System.out.println(ex.getMessage() + " is not a numeric value.");
System.exit(0);
}
}
}

Output of this program:


C:\vinod\xml>javac
exceptionHandle.java

C:\vinod\xml>java
exceptionHandle

For input string: "" is not a


numeric value.

An exception is an event that occurs and interrupts the normal flow of


instructions. That is exceptions are objects that store the information about
the occurrence of errors. When any kind of error or unusual condition occurs,
these exceptions are being thrown. Any exception used to occur earlier
always resulted in a program crash. However, some programming languages
like java have mechanisms for handling exceptions. This is known
as catching exception in Java. The exceptions that occur in the program can
be caught using try and catch block. Remember, the program will crash if
the exception would not be caught. There are three types of exceptions in
Java. These are -:

1. Checked Exceptions
2. The error
3. Runtime exception

Error and Runtime exceptions are known as unchecked exceptions. This


chapter covers how to throw an exception and catch it. A detailed
explanation on the types of exceptions and the advantages of the exceptions.
Basic I/O:
In this section we will learn about basic input and out put operations in Java.
Different kinds of sources and destinations are represented by a Stream like
disk files, devices, memory arrays etc. A Stream is a sequence of data.
An Input Stream is used by the program to read data from the source.
Similarly, a program uses an Output stream to write data to a destination. It
also supports different kinds of data including simple bytes, primitive data
types, objects etc. We will learn about I/O Steams and how to use them.
Concurrency:
Concurrency is generally used to perform multiple tasks simultaneously. In
this section we will learn how to write applications to perform multitasking.
There are two types of units of execution process and threads. Thread is the
most important unit in concurrent programming. There are many processes
and threads which are active in a computer system. However only one
threads executes at a time even in systems that only have a single execution
core.
Regular expression
The set of strings which are based on common characteristics are shared by
each string in the set. Basically, Regular expressions are are a set of strings.

This regular expression as a Java string, becomes "\\\\". That is 4 backslashes


to match a single one. As in literal Java strings the backslash is an escape
character. The literal string as a single backslash is denoted by "\\". In this
chapter we will learn to create a syntax for regular expressions and how to
use them.
Input And Output

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.

Classes and Descriptions:


BufferedInputStream It used for creating an internal buffer
array. It supports the mark and reset
methods.
BufferedOutputStream This class used for writes byte to
output stream. It implements a buffered
output stream.
BufferedReader This class provides read text from
character input stream and buffering
characters. It also reads characters,
arrays and lines.
BufferedWriter This class provides write text from
character output stream and buffering
characters. It also writes characters,
arrays and lines.
ByteArrayInputStream It contains the internal buffer and read
data from the stream.
ByteArrayOutputStream This class used for data is written into
byte array. This is implement in output
stream class.
CharArrayReader It used for char input stream and
implements a character buffer.
CharArrayWriter This class also implements a character
buffer and it uses an writer.
DataInputStream This class reads the primitive data
types from the input stream in a
machine format.
DataOutputStream This class writes the primitive data
types from the output stream in
machine format.
File This class shows a file and directory
pathnames.
FileDescriptor This class uses for create a
FileInputStream and FileOutputStream.
FileInputStream It contains the input byte from a file
and implements an input stream.
FileOutputStream It uses for writing data to a file and also
implements an output stream.
FilePermission It provides the permission to access a
file or directory.
FileReader This class used for reading characters
file.
FileWriter This class used for writing characters
files.
FilterInputStream This class overrides all methods of
InputStream and contains some other
input stream.
FilterOutputStream This class overrides all methods of
OutputStream and contains some other
output stream.
FilterReader It reads the data from the filtered
character stream.
FilterWriter It writes data from the filtered character
stream.
InputStream This class represents an input stream of
bytes.
InputStreamReader It reads bytes and decodes them into
characters.
LineNumberReader This class has a line numbers
ObjectInputStream This class used for recover the object to
serialize previously.
ObjectInputStream.GetField This class access to president fields
read form input stream.
ObjectOutputStream This class used for write the primitive
data types and also write the object to
read by the ObjectInputStream.
ObjectOutputStream.GetField This class access to president fields
write in to ObjectOutput.
ObjectStreamClass Serialization's descriptor for classes.
ObjectStreamField This class describes the serializable
field.
OutputStream This class represents an output stream
of bytes.
OutputStreamWriter It writes bytes and decodes them into
characters.
PipedInputStream In this class the data bytes are written
into piped output stream. This class
also connected into a piped output
stream.
PipedOutputStream This class also communicates the piped
input stream into piped output stream.
It creates communication between
both.
PipedReader It is a piped character-input stream.
PipedWriter It is a piped character-output stream.
PrintStream This class adds the functionality of
another output stream.
PrintWriter This class adds the functionality of
another input stream.
PushbackInputStream It also include the another function of
input stream. Such as: "push back" or
"unread" one byte.
PushbackReader This is a character stream reader and
reads the data push back into the
stream.
RandomAccessFile It supports both reading and writing to
a random access file.
Reader It used for reading character stream.
SequenceInputStream It represents the logical concatenation
of other input stream.
SerializablePermission This is a serializable permission class.
StreamTokenizer It takes an input stream and parse it
into "tokens" . The token to be allowed
at the read time.
StringReader This is a character string class. It has
character read source.
StringWriter This is also a character string class. It
uses to shows the output in the buffer.
Writer It uses for writing to character stream.

Exceptions for java.io package:


CharConversionException It provides detail message in the catch
block to associated with the
CharConversionException
EOFException This exception indicates the end of
file. When the file input stream to be
end then EOFException to be
occuted.
FileNotFoundException When the open file's pathname does
not find then this exception to be
occured.
InterruptedIOException When the I/O operations to
interrupted from any causes then it
becomes.
InvalidClassException Any problems to be created with
class, when the Serializing runtime to
be detected.
InvalidObjectException When the de-serialized objects failed
then it occurs.
IOException When the I/O operations to be failed
then it occurs.
NotActiveException The Serialization or deserialization
operations are not active then it
occurs.
NotSerializableException This exception when the instance is
required to a Serializable interface.
ObjectStreamException This is a supper class of all exception
class. It used for specific to Object
Stream Classes.
OptionalDataException When the reading data operations to
failed then it these exception occurs.
It is belonging to the serialized object
StreamCorruptedException It thrown when the control
information that was read form an
object stream vioaltes internal
consistency checks.
SyncFaieldException The sync operation is failed then
SyncFaieldException to be occure.
UnsupportedEncodingException The Character Encoding is not
supported.
UTFDataFormatException A molformed UTF-8 has been read in
a data input stream, it implemented by
data input interface.
WriteAbortedException In this exception to be thrown by the
ObjectStreamException during a write
operating.
Read Text from Standard IO: Java provides the standard I/O facilities for
reading text through either the file or keyboard in command line. This
program illustrates you how to use standard input to read the user input..
In this section, you will see how the standard I/O is used to input any thing
by the keyboard or a file. This is done using the readLine() method which is
the method of the BufferedReader class.
BufferedReader :
The BufferedReader class is the subclass of
the FilterReader class. BufferedReader class maintains the buffer and
buffer state. BufferedReader class supports
the read() and readLine() method for input text from a character-input stream.
The buffer size may be specified but the default buffer size is enough for
most purposes because the default buffer size of 8192 chars can be
overridden by the creator of the stream.
In this program, as you can see that the instance variable in of
the BufferedReader class which reads a single line of text from the input
stream.
Here is the code of the program :
import java.io.*;
public class ReadStandardIO{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter text : ");
String str = in.readLine();
System.out.println("You entered String : ");
System.out.println(str);
}
}

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.*;

class OnlyExt implements FilenameFilter{


String ext;

public OnlyExt(String ext){


this.ext="." + ext;
}

public boolean accept(File dir,String name){


return name.endsWith(ext);
}
}

public class FilterFiles{


public static void main(String args[]) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the directory name : ");
String dir = in.readLine();
System.out.println("Please enter file type : ");
String extn = in.readLine();
File f = new File(dir);
FilenameFilter ff = new OnlyExt(extn);
String s[] = f.list(ff);

for (int i = 0; i < s.length; i++)


{
System.out.println(s[i]);
}
}
}

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);

Here is the code of program :


import java.io.*;

public class CreateFile{

public static void main(String[] args) throws IOException{


BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the file name to create : ");
String file_name = in.readLine();
File file = new File(file_name);
boolean exist = file.createNewFile();
if (!exist)
{
System.out.println("File already exists.");
System.exit(0);
}
else
{
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
out.write(in.readLine());
out.close();
System.out.println("File created successfully.");
}
}
}

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:

1. An optional system-dependent prefix string,


such as a disk-drive specifier, "/" for the UNIX root directory,
or "\\" for a Win32 UNC pathname, and
2. A sequence of zero or more string names.

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.*;

public class CopyFile{


private static void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

//For Append the file.


// OutputStream out = new FileOutputStream(f2,true);

//For Overwrite the file.


OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];


int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("File has not mentioned.");
System.exit(0);
case 1: System.out.println("Destination file has not mentioned.");
System.exit(0);
case 2: copyfile(args[0],args[1]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}

Serializing an Object in Java: In this section, you will learn how to


Serialize an Object in java. Serialization refers to the method of saving the
object's sate into the file store or database. The serialized objects are JVM
independent and can be re-serialized by any JVM. In this case the "in
memory" java objects state are converted into a byte stream. This type of the
file can not be understood by the user. It is a special types of object i.e.
reused by the JVM (Java Virtual Machine).
This example shows you how to serialize any objects. This program takes a
file name and then serialize the object. This file is machine understandable.
Default serialization mechanism for an object writes the class of the object,
the class signature, and the values of all non-transient and non-static fields.
ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStrea
m(f));
Above code has been used to create the instance of the ObjectOutput class
with the ObjectOutputStream() constructor which takes the instance of
the FileOuputStream as a parameter.
The ObjectOutput interface is used by implementing
the ObjectOutputStream class. TheObjectOutputStream is constructed to
serialize the object.
writeObject():
Method writeObject() writes an object to the given stream.
Here is the code of program:
import java.io.*;

public class SerializingObject{


public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter File name : ");
String file = in.readLine();
System.out.print("Enter extention : ");
String ext = in.readLine();
String filename = file + "." + ext;
File f = new File(filename);
try{
ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStream(f));
ObjOut.writeObject(f);
ObjOut.close();
System.out.println("Serializing an Object Creation completed successfully.");
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
}

Deserializing an Object in java: Here, you will learn how to De-serialize


the Java object. This means, converting the serialized object into in-memory
java object. This program shows how to read any data or contents from the
serialized object or file. It takes a file name and then converts into java
object. If any exception occurs during reading the serialized file, it is caught
in the catch block.
ObjectInputStream obj = new ObjectInputStream(new FileInputStream
(f));
Above code of the program creates the instance of
the ObjectInputStream class to deserialize that file which had been
serialized by the ObjectOutputStream class. The above code creates the
instance using the instance of the FileInputStream class which holds the
specified file object which has to be deserialized because the
ObjectOutputStream() constructor needs the input stream.
readObject():
Method readObject() reads the object and restore the state of the object. This
is the method of theObjectOutputStream class and methods
of ObjectOutputStream class helps to traverse the object.
Here is a code of program :
import java.io.*;

public class DeserializingObject{


public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter File name : ");
String file = in.readLine();
System.out.print("Enter extention : ");
String ext = in.readLine();
String filename = file + "." + ext;
File f = new File(filename);
try{
ObjectInputStream obj = new ObjectInputStream(new FileInputStream(f));
System.out.println("The text : "+ obj.readObject());
obj.close();
System.out.println("Deserializing Operation Completly Successfully.");
}
catch(ClassNotFoundException e){
System.out.println(e.getMessage());
}
catch(FileNotFoundException fe){
System.out.println("File not found ");
}
}
}

to go in more details about I/O plz go through


"http://www.roseindia.net/java/example/java/io/".

Você também pode gostar