Unit 3 Oops
Unit 3 Oops
Unit 3 Oops
An exception is an unwanted or unexpected event that occurs during the execution of the
program, that disrupts the flow of the program.
For example, if a user is trying to divide an integer by 0 then it is an exception, as it is not
possible mathematically.
There are various types of interruptions while executing any program like errors, exceptions, and
bugs. These interruptions can be due to programming mistakes or due to system issues.
Depending on the conditions they can be classified as errors and exceptions.
1. Exception
• As mentioned earlier exceptions are unwanted conditions that disrupt the flow of the
program.
• Exceptions usually occur due to the code and can be recovered.
• Exceptions can be of both checked(exceptions that are checked by the compiler) and
unchecked(exceptions that cannot be checked by the compiler) type.
• They can occur at both run time and compile time.
In Java, exceptions belong to java.lang.Exception class.
2. Error
Java exceptions raised during the program execution are nothing but objects of the respective
exception class in the hierarchy shown above. The exceptions have a naming and inheritance
hierarchy to the main exception class in java i.e. Throwable class. All java exception objects
support the toString() method, which returns the full name of the exception class as an output to
the command prompt, which helps to understand the exceptional condition.
Whenever an exception has occurred inside a method, the method creates an exception object and
hands it over to JVM.
This object contains the name and description of the exception and the current state of the program
where the exception has occurred. This is called the process of object creation and handing it over
to JVM is known as throwing an Exception. This object is an exception that is further handled by
JVM.
When an exception is raised there is an ordered list of the methods that had been called by JVM to
get the method where the exception has occurred this list is called Call Stack.
JVM searches through this call stack to get the proper code to handle the occurred exception, this
code block is known as an Exception handler. When an appropriate handler is found JVM handles
the exception according to the code in the handler and shows the state of the program.
But if it is not able to find the handler JVM uses the default exception handler, which is part of the
run-time system. But this default exception handler throws an exception and terminates the
program abnormally.
2. Unchecked Exceptions
• Unchecked exceptions are those exceptions that are checked at run time by JVM, as the
compiler cannot check unchecked exceptions,
• The programs with unchecked exceptions get compiled successfully but they give
runtime errors if not handled.
• These are child classes of Runtime Exception Class.
• ArithmeticException, NullPointerException, NumberFormatException,
IndexOutOfBoundException are a few of the unchecked exceptions in Java.
try {
System.out.println(data);
} catch (Exception e) {
} finally {
2. throws keyword
• throws keyword in java is used in the signature of the method to indicate that this method
might throw one of the exceptions from java exception class hierarchy.
• throws keyword is used only for checked exceptions like IOException as using it with
unchecked exceptions is meaningless(Unchecked exceptions can be avoided by
correcting the programming mistakes.)
• throws keyword can be used to declare an exception.
Example: In case a user wants to set Age limit we can use custom exceptions and give the
required comment as an output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains
all the classes required for input and output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the
console.
1. System.out.println("simple message");
2. System.err.println("error message");
3. int i=System.in.read(); //returns ASCII code of 1st character
4. System.out.println((char)i); //will print the character
➔Byte Stream and Character Stream
There are two types of streams in Java- Byte Stream and Character Stream.
Byte streams in Java are used to perform input and output operations of 8-bit bytes while the
Character stream is used to perform input and output operations for 16-bits Unicode.
Character streams are useful in reading or writing text files which are processed character by
character.
Byte Streams are useful to read/write data from raw binary files.
➔Byte Stream
Byte Stream are Further divided into two parts:
1. OutputStream
• Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.
• Class Hierarchy for OutputStream:
OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts output bytes and
sends them to some sink.
BufferedOutputStream :
This is used for Buffered Output Stream.
DataOutputStream :
This contains method for writing java standard data types.
FileOutputStream :
This is used to write to a file.
PrintStream :
This contains the most used print() and println() method
2. InputStream
• Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
• Class Hierarchy for InputStream:
InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.
BufferedInputStream
It is used for Buffered Input Stream.
DataInputStream
It contains method for reading java standard datatypes.
FileInputStream
This is used to reads from a file.
Example: Copy the content of one file to another
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
try {
in = new FileInputStream("infile.txt");
out = new FileOutputStream("outfile.txt");
int c;
2. Writer Hierarchy
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}catch(IOException e){
System.out.println(“Input Output Exception”);
}finally {
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
➔InputStreamReader and OutputStreamWritter
The InputStreamReader class works with other input streams. It is also known as a bridge between
byte streams and character streams. This is because the InputStreamReader reads bytes from the
input stream as characters.
import java.io.InputStreamReader;
import java.io.FileInputStream;
class Main {
public static void main(String[] args) {
try {
input.read(array);
System.out.println("Data in the stream:");
System.out.println(array);
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
The OutputStreamWriter class works with other output streams. It is also known as a bridge
between byte streams and character streams. This is because the OutputStreamWriter converts its
characters into bytes.
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
try {
output.write(data);
output.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}