Oopjava Unit III
Oopjava Unit III
By
Dr. Srikanth Lakumarapu
Associate Professor
Dept. Of CSE
CVR COLLEE OF ENGINEERING
Error
Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try
to handle errors.
Exception Handling
• Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions.
• Exceptions can be caught and handled by the program. When an exception
occurs within a method, it creates an object.
• This object is called the exception object.
• It contains information about the exception, such as the name and description
of the exception and the state of the program when the exception occurred.
Exception Handling
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Out of bound
• Null reference
• Type mismatch
• Opening an unavailable file
• Database errors
• Arithmetic errors
Types of Exceptions
Exception class Hierarchy
Methods to print the Exception
information
1. printStackTrace():
• This method prints exception information in the format of the Name of the
exception: description of the exception, stack trace.
2. toString()
• The toString() method prints exception information in the format of the Name
of the exception: description of the exception.
• 3. getMessage()
• The getMessage() method prints only the description of the exception.
Default Exception Handling
• Exception Handling automatically done by Java Runtime Environment is called
Default Exception Handling. It can be done in the following way:
• Whenever inside a method, if an exception has occurred, the method creates an
Object known as an Exception Object and hands it off to the run-time
system(JVM).
• Creating the Exception Object and handling it in the run-time system is called
throwing an Exception.
• The run-time system searches for the appropriate handler, if it not found then
the run-time system handover the Exception Object to the default exception
handler, which is part of the run-time system.
• This handler prints the exception information and terminates the
program abnormally.
Default Exception Handling
Custom Exception Handling
• Exception handling done by the user is called custom exception handling.
• It can be done in java by using these keywords- try, catch, throw, throws,
and finally.
• Program statements that you think can raise exceptions are contained within a try
block.
• If an exception occurs within the try block, it is thrown. System-generated exceptions
are automatically thrown by the Java run-time system. To manually throw an
exception, use the keyword throw.
• Your code can catch this exception (using catch block) and handle it in some rational
manner.
• Any exception that is thrown out of a method must be specified as such by a throws
clause.
• Any code that absolutely must be executed after a try block completes is put in a
finally block.
Summery of Exception Handling
User Defined Exception
• Creating our own Exception is known as a custom exception or
user-defined exception.
1. Define the Custom Exception class by extending the
Exception Class or RuntimeException class
• Provide constructors to initialize the exception with messages or causes.
2. Throw the Custom Exception
3`. Catch the Custom Exception
Built in Packages
Built in Packages
I/O STREAMS
• Java I/O (Input and Output) is used to process the input and produce the output.
• Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
• A stream is a sequence of data. In Java, a stream is composed of bytes.
• In Java, 3 standered streams are available. All these streams are attached with the
console.
• 1) System.in: This is the standard input stream that is used to read characters from
the keyboard or any other standard input device.
• 2) System.out: This is the standard output stream that is used to produce the result
of a program on an output device like the computer screen.
• 3) System.err: This is the standard error stream that is used to output all the error
data that a program might throw, on a computer screen or any standard output device.
TYPES OF STREAMS BASED ON FILE
Depending on the types of file, Streams can be divided into two primary classes
1. Byte Stream: This is used to process data byte by byte (8 bits).
• Byte streams in Java are used for handling raw binary data. They provide a way
to read and write bytes, which makes them suitable for various types of files,
including images, audio files, and other binary formats.
1. Character Stream: Character streams handle text data and read/write data
in characters. They use Unicode, making them suitable for
internationalization.
• Ideal for reading and writing text files or string data, ensuring proper encoding
and decoding of characters.
TYPES OF STREAMS BASED ON FILE
TYPES I/O STREAMS
1. Input Stream: These streams are used to read data that must be taken as an
input from a source array or file or any peripheral device. For eg.,
FileInputStream, BufferedInputStream, ByteArrayInputStream etc.
2. Output Stream: These streams are used to write data as outputs into an array
or file or any output peripheral device. For eg., FileOutputStream,
BufferedOutputStream, ByteArrayOutputStream etc.
Input Stream classes hierarchy
InputStream class
Java InputStream class is the superclass of all the io classes i.e. representing an
input stream of bytes.
It is an abstract class.
Declaration:
public abstract class InputStream extends Object implements Closeable
{ }
Methods of InputStream class:
int read(): Reads the next byte of data from the input stream. Returns the byte as
an integer in the range 0 to 255 or -1 if the end of the stream is reached.
int read(byte[] b): Reads some number of bytes from the input stream and stores
them into the specified byte array. Returns the total number of bytes read into the
buffer, or -1 if the end of the stream has been reached.
InputStream class
int read(byte[] b, int off, int len): Reads up to len bytes of data from the input
stream into an array of bytes starting at the specified offset off. Returns the
number of bytes read or -1 if the end of the stream has been reached.
int available(): Returns an estimate of the number of bytes that can be read from
the input stream without blocking.
void mark(int readlimit): Marks the current position in the input stream.
Subsequent calls to the reset() method will reposition the stream to this marked
location as long as the number of bytes read does not exceed readlimit.
void close(): Closes the input stream and releases any system resources
associated with it.
long skip(long n): void reset(): boolean markSupported(): long skip(long n):
Output Stream classes hierarchy
OutputStream class
OutputStream class is an abstract class.
It is the superclass of all classes representing an output stream of bytes.
An output stream accepts output bytes and sends them to some sink.
Methods of OutputStream class
void write(int b): Writes the specified byte to this output stream.
void write(byte[] b): Writes b.length bytes from the specified byte array to
this output stream.
void write(byte[] b, int off, int len): Writes len bytes from the specified byte
array starting at offset off to this output stream.
void flush(): Flushes the output stream and forces any buffered output bytes
to be written out.
void close(): Closes the output stream and releases any system resources
associated with it.
FileInputStream class
FileInputStream class provide mechanism to read byte streams from a file.
It provides a convenient way to read data from files in a binary format.
Constructors:
FileInputStream(String name): Creates a FileInputStream by opening a connection to
an actual file, using the file's pathname.
FileInputStream(File file): Creates a FileInputStream from a File object.
Methods:
int read(): Reads the next byte of data from the input stream and returns it as an
integer.
int read(byte[] b): Reads a certain number of bytes from the input stream into an
array of bytes.
int read(byte[] b, int off, int len): Reads up to len bytes of data from the input stream
into an array of bytes, starting at the specified offset.
void close(): Closes the input stream and releases any system resources associated
with it.
FileInputStream class
import java.io.FileInputStream;
import java.io.IOException;
FileInputStream fis = null;
try {
fis = new FileInputStream("example.txt");
int data;
System.out.print((char) data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream class
The FileOutputStream class in Java, part of the java.io package, is used to write
byte streams to a file.
It is particularly useful for writing binary data, such as images or other
non-text files.
As a subclass of OutputStream, it provides methods for writing bytes to the
output stream.
Constructor:
FileOutputStream(String name): Creates a FileOutputStream to write to the
file specified by the pathname.
FileOutputStream(File file): Creates a FileOutputStream from a File object.
FileOutputStream(String name, boolean append): Creates a
FileOutputStream to write to the file with the option to append to the existing
content.
FileOutputStream class
Methods:
void write(int b): Writes the specified byte to the output stream.
void write(byte[] b): Writes the entire byte array to the output stream.
void write(byte[] b, int off, int len): Writes a portion of a byte array,
starting at the specified offset and writing len bytes.
void flush(): Flushes the output stream, forcing any buffered output
bytes to be written out.
void close(): Closes the output stream and releases any system
resources associated with it.
FileOutputStream class
import java.io.FileOutputStream;
import java.io.IOException;
try {
fos.write(data.getBytes());
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayInputStream class
The `ByteArrayInputStream` class in Java, part of the `java.io` package,
allows an application to create an input stream from a byte array.
This is useful when you want to read data from a byte array as if it were
an input stream, making it easy to process data in memory.
As Subclass of InputStream it Inherits methods from `InputStream`,
making it easy to read data using standard input stream operations.
Constructors:
1. ByteArrayInputStream(byte[] buf): Creates a
`ByteArrayInputStream` initialized with the specified byte array.
2. ByteArrayInputStream(byte[] buf, int offset, int length): Creates a
`ByteArrayInputStream` with a specified portion of the byte array,
allowing you to specify an offset and the number of bytes to read.
ByteArrayInputStream class
Basic Methods:
int read(): Reads the next byte of data from the input stream and returns
it as an integer.
int read(byte[] b): Reads bytes into the specified byte array.
int read(byte[] b, int off, int len): Reads up to `len` bytes into the
specified byte array, starting at the given offset.
int available(): Returns the number of bytes that can be read without
blocking.
void mark(int readlimit): Marks the current position in the stream.
void reset(): Resets the stream to the most recent mark.
void close(): Closes the stream (no effect since it's memory-based).
ByteArrayOutputStream class
The `ByteArrayOutputStream` class in Java, part of the `java.io` package,
is used to write data to a byte array in memory.
It provides an easy way to collect output data and manipulate it as a
byte array without need of file I/O.
This is particularly useful for scenarios where you want to construct byte
arrays dynamically.
Data written to a `ByteArrayOutputStream` is stored in a byte array in
memory.
The underlying byte array grows automatically as you write more data
than its current capacity.
ByteArrayOutputStream class
Constructors: