Unit III Oops
Unit III Oops
EXCEPTION HANDLING
EXCEPTION:
An exception is an abnormal condition that arises in a code sequence at run time and
alters the normal program flow.
In other words, an exception is a run-time error.
Exception handling works by transferring the execution of a program to an appropriate
exception handler when an exception occurs.
Exception-Handling Fundamentals:
Exception in JAVA
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code. When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error. That method may choose to
handle the exception itself, or pass it on. Either way, at some point, the exception is caught and
processed. Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code. Manually generated exceptions are typically used to report some error
condition to the caller of a method.
Exception-Handling Keywords:
Java exception handling is managed via five keywords:
try - Set of statement to be monitored for exceptions
catch - Exception handler , handle the exception
throw -Used to manually throw an exception
throws - Throw an exception out of a method
finally – Will be executed absolutely
Note: try and catch is a indivisible unit. A try without catch is an error but catch can be replaced
by finally. A catch without try is an error.
General form of an exception-handling block:
try
{
// block of code to monitor for errors
// it is the "guarded region.
//"Put code here that might cause some kind of exception.
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
// Put code here that handles this exception.
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
// Put code here that handles this exception.
}
// ...
finally
{
// block of code to be executed after try block ends. //Put code here to release any
resource we allocated in the try clause.
}
// Some other unguarded (normal, non-risky) code begins here
Catch :
Catch is used to define a block of code that handle an exception and it is called Exception
Handler. One or more catch clauses match a specific exception to a block of code that handles
it.
Finally :
A finally block encloses code that is always executed at some point after the try block, whether
an exception was thrown or not. This is the right place to close your files, release your network
sockets, and perform any other cleanup your code requires. If the try block executes with no
exceptions, the finally block is executed immediately after the try block completes. If there was
an exception thrown, the finally block executes immediately after the proper catch block
completes.
throw:
Java throw keyword is used throw an exception explicitly in the code, inside the function or the
block of code.
Throws:
Java throws keyword is used in the method signature to declare an exception which might be
thrown by the function while the execution of the code.
Syntax:
try
{
block of code to monitor for errors
}
catch (ExceptionType exOb)
{
Block of code to handle exception of type
ExceptionType
}
ii. Try with multiple catches
try
{
block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
Block of code to handle exception of type ExceptionType1
}
catch (ExceptionType2 exOb)
{
Block of code to handle exception of type ExceptionType2
}
try
{
block of code to monitor for errors
}
finally
{
Block of code will be executed absolutely whether or not an exception
}
try
{
block of code to monitor for errors
}
catch (ExceptionType exOb)
{
Block of code to handle exception of type ExceptionType
}
finally
{
Block of code will be executed absolutely whether or not an exception
}
iv.Try with multiple catches and with finally
try
{
block of code to monitor for errors
}
catch (ExceptionType exOb1)
{
Block of code to handle exception of type ExceptionType1
}
catch (ExceptionType exOb2)
{
Block of code to handle exception of type ExceptionType2
}
finally
{
Block of code will be executed absolutely whether or not an exception
}
3.2 EXCEPTION HIERARCHY
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top
of the exception class hierarchy. Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches. One branch is headed by Exception and the other branch is
topped by Error.
Exception class :
This class is used for exceptional conditions that user programs should catch. This is also the
class that you will subclass to create your own custom exception types. There is an important
subclass of Exception, called RuntimeException. Exceptions of this type are automatically
defined for the programs that you write and include things such as division by zero and invalid
array indexing.
Error class:
The other branch is topped by Error, which defines exceptions that are not expected to be caught
under normal circumstances by your program. Exceptions of type Error are used by the Java run-
time system to indicate errors having to do with the run-time environment, itself. Stack overflow
is an example of such an error. Exceptions of type Errors are typically created in response to
catastrophic failures that cannot usually be handled by your program.
STACK TRACE:
The stack trace will always show the sequence of method invocations that led up to the
error. For example, here is another version of the preceding program that introduces the same
error but in a method separate from main( ):
class Exc1 {
static void subroutine() {
int d = 0;
int a = 10 / d;
}
public static void main(String args[]) {
Exc1.subroutine();
}
}
The resulting stack trace from the default exception handler shows how the entire call stack is
displayed:
java.lang.ArithmeticException: / by zero
at Exc1.subroutine(Exc1.java:4)
at Exc1.main(Exc1.java:7)
As you can see, the bottom of the stack is main’s line 7, which is the call to subroutine( ), which
caused the exception at line 4. The call stack is quite useful for debugging, because it pinpoints
the precise sequence of steps that led to the error.
To guard against and handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately following the try block, includes a catch clause that specifies the
exception type that you wish to catch. To illustrate how easily this can be done, the following
program includes a try block and a catch clause that processes the ArithmeticException
generated by the division-by-zero error:
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (Arithm eticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
Output2:
C:\>java MultiCatch TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}
}
that uses nested try statements:
As you can see, this program nests one try block within another.
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42
throw
used to throw an exception explicitly. The general form of throw is shown here:
Syntax:
throw ThrowableInstance;
// Demonstrate throw.
class Demo {
public static void main(String args[])
{
int a=5,b=0,c;
try {
c=a/b;
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("Caught Exception : divide by zero");
}
}
Output:
throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You do this
by including a throws clause in the method’s declaration. A throws clause lists the types of
exceptions that a method might throw.
This is the general form of a method declaration that includes a throws clause:
Output:
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo
finally:
frinally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block. The finally block will execute whether or not an
exception is thrown. If an exception is thrown, the finally block will execute even if no catch
statement matches the exception. This can be useful for closing file handles and freeing up any
other resources that might have been allocated at the beginning of a method with the intent of
disposing of them before returning. The finally clause is optional. However, each try statement
requires at least one catch or a finally clause.
Here is an example program that shows three methods that exit in various ways, none without
executing their finally clauses:
// Demonstrate finally.
class Exc3
{
public static void main(String args[])
{
int d, a;
try
{
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero" + e);
}
//System.out.println("After catch statement.");
finally
{
System.out.println("Finllay block executed");
}
System.out.println("After catch statement.");
}
}
OUTPUT :
Division by zero. java.lang.ArithmeticException: / by zero
Finllay block executed
After catch statement.
Unchecked exceptions
Checked exceptions+
Unchecked Exceptions :
Unchecked exceptions are not checked at compile time. It means if your program is throwing
an unchecked exception and even if you didn’t handle/declare that exception, the program won’t
give a compilation error. All Unchecked exceptions are direct sub classes
of RuntimeException class.
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible
type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined
enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current
thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
TypeNotPresentException Type not found.
UnsupportedOperationException An unsupported operation was encountered.
// Demonstrate Unchecked exceptions
.
class Exc3
{
public static void main(String args[])
{
int d, a;
try
{
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
// catch divide-by-zero error
System.out.println("Division by zero" + e);
}
//System.out.println("After catch statement.");
finally
{
System.out.println("Finllay block executed");
}
System.out.println("After catch statement.");
}
}
OUTPUT :
Division by zero. java.lang.ArithmeticException: / by zero
Finllay block executed
After catch statement.
Checked Exception :
Checked exceptions are checked at compile-time. It means if a method is throwing a checked
exception then it should handle the exception using try-catch block or it should declare the
exception using throws keyword, otherwise the program will give a compilation error.
Java’s Checked Exceptions Defined in java.lang
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
FileNotFound Exception A requested File does not exist.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class
or interface.
InterruptedException One thread has been interrupted by another
thread.
NoSuchFieldException A requested field does not exist.
Example program:
import java.lang.*;
class Student implements Cloneable{
int rollno;
String name;
void getdata(){
rollno=121;
name="RAM";
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
}
class Main
{
public static void main(String args[])
{
try
{
Student s1=new Student();
s1.getdata();
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException e)
{
System.out.println(e);
}
}
}
Checked exceptions Unchecked exceptions
Checked exceptions occur at compile time. Unchecked exceptions occur at runtime.
A checked exception is checked by the The compiler does not check these type of
compiler exception.
These types of exception can be handled at the These types of exceptions cannot be a catch or
time of compilation handle at the time of compilation, because they
get generated by the mistakes in the program
They are the sub-class of the exception class They are runtime exceptions and hence are not
a part of the Exception class.
Here, the JVM needs the exception to catch Here, the JVM does not require the exception
and handle. to catch and handle
The Exception class does not define any methods of its own. It does, of course, inherit those
methods provided by Throwable. Thus, all exceptions, including those that you create, have the
methods defined by Throwable available to them. They are shown in Table.
Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a
completed stack trace. This object can be
rethrown.
Throwable getCause( ) Returns the exception that underlies the current
exception. If there is no underlying exception,
null is returned.
String getLocalizedMessage( ) Returns a localized description of the exception.
String getMessage( ) Returns a description of the exception.
StackTraceElement[ ] getStackTrace() Returns an array that contains the stack trace, one
element at a time, as an array of
StackTraceElement. The method at the top of the
stack is the last method called before the
exception was thrown. This method is found in
the first element of the array. The
StackTraceElement class gives your program
access to information about each element in the
trace, such as its method name.
Throwable initCause(Throwable causeExc) Associates causeExc with the invoking exception
as a cause of the invoking exception. Returns a
reference to the exception
TABLE : The Methods Defined by Throwable
You may also wish to override one or more of these methods in exception classes that you create.
Exception defines four constructors. The two are shown here:
Exception( )
Exception(String msg)
The first form creates an exception that has no description.
The second form lets you specify a description of the exception.
Summary :
An exception is an abnormal condition that arises in a code sequence at run time and
alters the normal program flow.
Exception-Handling Keywords:
o try - Set of statement to be monitored for exceptions
o catch - Exception handler , handle the exception
o throw -Used to manually throw an exception
o throws - Throw an exception out of a method
o finally – Will be executed absolutely
Any exception that is not caught by your program will ultimately be processed by the
default handler.
The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program.
The stack trace will always show the sequence of method invocations that led up to
the error.
Once an exception is thrown, program control transfers out of the try block into the catch
block and execution never “returns” to the try block from a catch.
INPUT / OUTPUT BASICS:
Text- based IO :
Handle input and output in terms of 16 bit unsigned character.
It works with human readable character – such as source code of the program.
To handle Text- based IO java provides a set of Character stream classes.
Binary based IO
Handle input and output in terms of byte(8 bit).
Suitable for reading or writing binary data – such as bit pattern of an image.
To handle binary- based IO java provides a set of Byte stream classes.
STREAMS:
Streams are ordered sequence of data that have a source (input stream) or destination
(output stream).
A stream is an abstraction that either produces or consumes information.
A stream is linked to a physical device by the Java I/O system.
An input stream can abstract many different kinds of input: from a disk file, a keyboard,
or a network socket.
An output stream may refer to the console, a disk file, or a network connection.
Byte streams provide a convenient means for handling input and output of bytes. Byte streams
are used, for example, when reading or writing binary data – such as bit pattern of an image.
Character streams provide a convenient means for handling input and output of characters .It
works with human readable character – such as source code of the program.
InputStream class:
InputStream is an abstract class that defines Java’s model of streaming byte input Most of the
methods in this class will throw an IOException on error conditions. (The exceptions are
mark( ) and markSupported( ).) Table shows the methods in InputStream.
Method of Input stream:
OutpuStream class:
OutputStream is an abstract class that defines streaming byte output. Most of the methods in
this class return void and throw an IOException in the case of errors. (The exceptions are
mark( ) and markSupported( )) Table shows the methods in OutputStream.
Table
Reader :
Reader is an abstract class that defines Java’s model of streaming character input. All of the
methods in this class (except for markSupported( )) will throw an IOException on error
conditions. Table 19-3 provides a synopsis of the methods in Reader.
Writer :
Writer is an abstract class that defines streaming character output. All of the methods in this
class throw an IOException in the case of errors. Table 19-4 shows a synopsis of the methods in
Writer.
READING AND WRITING CONSOLE:
BufferedReader :
To obtain a character based stream that is attached to the console, Java has a class called a
BufferedReader. the following line of code creates a BufferedReader that is connected to the
keyboard:
Syntax:
int read( ) throws IOException
it reads a character from the input stream and returns it as an integer value. It returns –1 when the
end of the stream is encountered. it can throw an IOException.
write()
void write(int byteval)
This method writes to the stream the byte specified by byteval. Although byteval is declared as
an integer, only the low-order eight bits are written. You will not often use write( ) to perform
console output (although doing so might be useful in some situations), because print( ) and
println( ) are substantially easier to use.
Example 1:
import java.io.*;
class IOExample
{
public static void main(String args[]) throws IOException
{
int a,b,c;
// Step 1. Create an object for BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Step 2. use read() or readLine() to read the inputs
System.out.println("Enter the value of A:");
a = Integer.parseInt(br.readLine());
System.out.println("Enter the value of B:");
b = Integer.parseInt(br.readLine());
c= a+ b;
System.out.println("sum ="+ c);
}
}
Output :
Enter the value of A:
5
Enter the value of B:
6
sum =11
Example 2:
Write a java program using stream to find sum of 3 numbers, find largest and smallest of 3
numbers and test whether third number is product of first and second numbers.
import java.io.*;
class IODemo
{
int a,b,c,sum,product;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
void input()
{
try
{
void findLarger()
{
if (a>b && a>c)
{
System.out.println("A is Greatest");
}
else if(b>c)
{
System.out.println("B is Greatest");
}
else
{
System.out.println("C is Greatest");
}
}
void findSmaller()
{
if (a<b && a<c)
{
System.out.println("A is Smallest");
}
else if(b<c)
{
System.out.println("B is Smallest");
}
else
{
System.out.println("C is Smallest");
}
void findProduct()
{
product = a*b;
if(c==product)
{
System.out.println("C is the product of A and B");
}
else
{
System.out.println("C is NOT the product of A and B");
}
Output :
Enter the value of A:
2
Enter the value of B:
4
Enter the value of C:
5
Sum of A,B,C = 11
C is Greatest
A is Smallest
C is NOT the product of A and B.
Reading and writing files in java can be done using following classes.
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
FileReader(String fileName) throws FileNotFoundException
FileWriter(String fileName) throws FileNotFoundException
Reading files:
Example program:
/*This program, read the content file and display it to console. */
import java.io.*;
class FileDemo
{
public static void main(String args[])
{
try
{
/*Create an object for FileInputStream, it throws FileNotFoundException if file is unavailable */
int c;
/*The method close() closes the file input stream It throws IOException*/
fin.close();
}
catch(IOException e)
{
System.out.println("File not found " + e);
}
}
}
Output:
Chennai
Delhi
Mumbai
Kolkata
Input File : file1.txt
Output:
File not found java.io.FileNotFoundException: k:\file1.txt (The system cannot find the file
specified)
/*The method close() closes the file input stream and file output stream It throws IOException*/
fin.close();
fout.close();
}
catch(IOException e)
{
System.out.println("File not found " + e);
}
}
}
Input File : file1.txt
Chennai
Delhi
Mumbai
Kolkata
Output:
File was successfully copied.
Explanation:
The above program creates a new file named file2.txt.
Output File : file2.txt
Chennai
Delhi
Mumbai
Kolkata