[go: up one dir, main page]

0% found this document useful (0 votes)
5 views65 pages

Oops U3

The document covers exception handling and input/output (I/O) in Java, detailing types of exceptions, keywords for handling them, and the exception hierarchy. It explains the concept of streams for I/O operations, differentiating between byte and character streams, and provides examples of built-in exceptions. Additionally, it discusses creating custom exceptions, using the Console class for user input, and the PrintWriter class for formatted output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views65 pages

Oops U3

The document covers exception handling and input/output (I/O) in Java, detailing types of exceptions, keywords for handling them, and the exception hierarchy. It explains the concept of streams for I/O operations, differentiating between byte and character streams, and provides examples of built-in exceptions. Additionally, it discusses creating custom exceptions, using the Console class for user input, and the PrintWriter class for formatted output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

UNIT-III

EXCEPTION HANDLING AND I/O


Exceptions
• An exception is an unwanted or
unexpected event, which occurs
during the execution of a program
at run time, that disrupts the
normal flow of the program’s
instructions.
Exceptions
Exception types
• Checked exceptions − A checked exception is an exception that
occurs at the compile time, also called as compile time (static time)
exceptions.
• Unchecked exceptions − An unchecked exception is an exception that
occurs at run time, also called as Runtime Exceptions. These include
programming bugs, such as logic errors or improper use of an API.
• Errors − Errors are not exceptions, but problems may arise beyond
the control of the user or the programmer.
Exception Hierarchy

• The java.lang.Throwable class


is the root class of Java
Exception hierarchy which is
inherited by two subclasses:
Exception and Error.
Exception Keywords
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code.
catch The "catch" block is used to handle the exception.
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.


throws The "throws" keyword is used to declare exceptions.
Throwing and Catching Exceptions
• Try/catch block
• Multiple catch
• Nested try block
• Finally block
• Throw keyword
• The Throws/Throw Keywords
Throwing and Catching Exceptions -
Try/catch block
• Java try block is used to Syntax
enclose the code that might try
{
throw an exception. It must
// the code you think can raise an
be used within the method. exception
Java try block must be }
followed by either catch or catch (ExceptionType exOb)
finally block. {
// exception handler for Exception
}
Throwing and Catching Exceptions -
Multiple catch
• If you have to perform Syntax
different tasks at the try
{
occurrence of different
}
Exceptions, use java multi catch (ExceptionType1 exOb)
catch block. {
}
catch (ExceptionType2 exOb)
{
}
Throwing and Catching Exceptions -
Nested try block
Syntax
• The try block within a try try
block is known as nested try {
block in Java. Sometimes a try
{}
situation may arise where a
catch (ExceptionType1 exOb)
part of a block may cause one {
error and the entire block }
itself may cause another error }
catch (ExceptionType2 exOb)
{}
Throwing and Catching Exceptions -
Finally block
• The try block within a try Syntax
block is known as nested try try
{
block in Java. Sometimes a
}
situation may arise where a catch (ExceptionType exOb)
part of a block may cause one {
error and the entire block }
itself may cause another error finally // optional
{
}
Throwing and Catching Exceptions -
Throw keyword
• The Java throw keyword is Syntax
used to explicitly throw an throw ThrowableInstance;
exception.
• Here, ThrowableInstance
must be an object of type
Throwable or a subclass of
Throwable.
Throwing and Catching Exceptions - 6 The
Throws/Throw Keywords
• If a method does not handle a checked exception, the method must be
declared using the throws keyword.
• The throws keyword appears at the end of a method’s signature.

Syntax
return type function name() throws Exception_name
Built-in exceptions
Exceptions Description
ArithmeticException It is thrown when an exceptional condition has
occurred in an arithmetic operation.
ArrayIndexOutOfBound It is thrown to indicate that an array has been
Exception accessed with an illegal index.
ClassNotFoundException This Exception is raised when we try to access a
class whose definition is not found.
FileNotFoundException This Exception is raised when a file is not
accessible or does not open.
IOException It is thrown when an input-output operation failed
or interrupted.
Built-in exceptions
Exceptions Description
InterruptedException It is thrown when a thread is waiting, sleeping, or
doing some processing, and it is interrupted.
NoSuchFieldException It is thrown when a class does not contain the
field (or variable) specified.
NoSuchMethodException It is thrown when accessing a method which is
not found.
NullPointerException This exception is raised when referring to the
members of a null object. Null represents nothing.
Built-in exceptions
Exceptions Description
IOException It is thrown when an input-output operation failed
or interrupted.
NumberFormatException This exception is raised when a method could not
convert a string into a numeric format.
RuntimeException This represents any exception which occurs
during runtime.
StringIndexOutOfBounds It is thrown by String class methods to indicate
Exception that an index is either negative than the size of the
string
this keyword
• this is a reference variable that refers to the current object.
• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from the method.
Creating own Exceptions
• To create own exceptions in Java, the following points should be
followed when writing our own exception classes −
• All exceptions must be a child of Throwable.
• If we want to write a checked exception that is automatically enforced
by the Handle or Declare Rule, we need to extend the Exception class.
• If we want to write a runtime exception, we need to extend the
RuntimeException class.
Creating own Exceptions
Syntax
class MyException extends Exception
{
}

We need to extend the predefined Exception class to create your own


Exception. These are considered to be checked exceptions.
StackTraceElement
• The StackTraceElement class element represents a single stack frame
which is a stack trace when an exception occurs.
• Extracting stack trace from an exception could provide useful
information such as class name, method name, file name, and the
source-code line number.
• The getStackTrace( ) method of the Throwable class returns an array
of StackTraceElements.
StackTraceElement
Method Description
boolean equals(Object obj) Returns true if the invoking StackTraceElement is
the same as the one passed in obj.
String getClassName() Returns the class name of the execution point.
String getFileName( ) Returns the filename of the execution point.
int getLineNumber( ) Returns the source-code line number of the
execution point.
String getMethodName( ) Returns the method name of the execution point.
String toString( ) Returns the String equivalent of the invoking
sequence.
Input / Output Basics
• Java I/O (Input and Output) is used to process the input and produce
the output.
• Java uses the concept of stream to make I/O operation fast.
• All the classes required for input and output operations are declared in
java.io package.
Input / Output Basics - Streams
• A stream can be defined as a sequence of data. The Input Stream is
used to read data from a source and the OutputStream is used for
writing data to a destination.
Input / Output Basics - Streams
Java defines two types of streams. They are,
• 1. Byte Stream : It is used for handling input and output of 8 bit
bytes. The frequently used classes are FileInputStream and
FileOutputStream.
• 2. Character Stream : It is used for handling input and output of
characters. Character stream uses 16 bit Unicode. The frequently used
classes are FileReader and File Writer.
Byte Streams - InputStream
Byte Streams - InputStream
Class Description
BufferedInputStream Contains methods to read bytes from the buffer.
ByteArrayInputStream Contains methods to read bytes from a byte
array.
DataInputStream Contains methods to read Java primitive data
types.
FileInputStream Contains methods to read bytes from a file.
Byte Streams - InputStream
Class Description
FilterInputStream Contains methods to read bytes from other input
streams which it uses as its basic source of data.
ObjectInputStream Contains methods to read objects.
PipedInputStream Contains methods to read from a piped output
stream.
SequenceInputStream Contains methods to concatenate multiple input
streams and then read from the combined
stream.
Byte Streams - InputStream
Method Description
public abstract int read() Reads the next byte of data from the input
throws IOException stream. It returns -1 at the end of file.
public int available() Returns an estimate of the number of bytes that
throws IOException can be read from the current input stream.
public void close() throws Close the current input stream
IOException
Byte Streams - OutputStream
• OutputStream class is an abstract class. It is the super class of all
classes representing an output stream of bytes.
Byte Streams - OutputStream
Class Description
BufferedOutputStream Contains methods to write bytes into the buffer
ByteArrayOutputStream Contains methods to write bytes into a byte
array
DataOutputStream Contains methods to write Java primitive data
types
FileOutputStream Contains methods to write bytes to a file
Byte Streams - OutputStream
Class Description
FilterOutputStream Contains methods to write to other output streams
ObjectOutputStream Contains methods to write objects
PipedOutputStream Contains methods to write to a piped output stream
PrintStream Contains methods to print Java primitive data types
Byte Streams - OutputStream
Method Description
public void write(int) throws Write a byte to the current output stream.
IOException
public void write(byte[]) Write an array of byte to the current output
throws IOException stream.
public void flush() throws Flushes the current output stream.
IOException
public void close() throws close the current output stream.
IOException
Character Stream - Reader
• Reader classes are used to read 16-bit unicode characters from the
input stream.
• The Reader class is the superclass for all character-oriented input
stream classes.
Reader class Description
BufferedReader Contains methods to read characters from the buffer
FileReader Contains methods to read from a file
InputStreamReader Contains methods to convert bytes to characters
Reader Abstract class that describes character stream input
Character Stream - Reader
Method Description
int read() returns the integral representation of the next
available character of input.
int read (char buffer []) attempts to read buffer. length characters into the
buffer and returns the total number of characters
successfully.
int read (char buffer [], attempts to read ‘nChars’ characters into the
int loc, int nChars) buffer starting at buffer [loc] and returns the total
number of characters successfully read.
long skip (long nChars) skips ‘nChars’ characters of the input stream and
returns the number of actually skipped characters
void close () closes the input source.
Character Stream - Writer
• Writer classes are used to write 16-bit Unicode characters onto an
output stream.
• The Writer class is the superclass for all character-oriented output
stream classes.
Writer class Description
BufferedWriter Contains methods to write characters to a buffer
FileWriter Contains methods to write to a file
OutputStreamReader Contains methods to convert from bytes to character
PrintWriter Output stream that contains print( ) and println( )
Writer Abstract class that describes character stream output
Character Stream - Writer
Method Description
void write () writes data to the output stream
void write (int i) Writes a single character to the output stream
void write (char buffer [] ) writes an array of characters to the output
stream
void write(char buffer [],int writes ‘n’ characters from the buffer starting at
loc, int nChars) buffer [loc] to the output stream
void close () closes the output stream. If an attempt is made
to perform writing operation even after closing
the stream then it generates IOException
Predefined Streams
• Standard Input − refers to the standard InputStream which is the
keyboard by default represented as System.in.
• Standard Output − refers to the standard OutputStream by default
represented as System.out.
• Standard Error − This is used to output the error data produced by the
user’s program represented as System.err.
Reading in console
• In Java, there are three different ways for reading input from the user
in the command line environment(console).
- 1.Using Buffered Reader Class
- 2. Using Scanner Class
- 3. Using Console Class
Using Buffered Reader Class
• This method is used by wrapping the System.in (standard input
stream) in an InputStreamReader which is wrapped in a
BufferedReader, we can read input from the user in the command line.
Using Scanner Class
• The Scanner class is to parse primitive types and strings using regular
expressions, however it is also can be used to read input from the user
in the command line.
Using Console Class
• It has been becoming a preferred way for reading user’s input from the
command line.
• In addition, it can be used for reading password-like input without
echoing the characters entered by the user
Assignment
• Write a Java program to define a own exception that must be thrown if
the entered product weight is less than 100. (Get the product weight
from the user).
• Write a Java program to find the length of the each word in a file. (Use
space as delimiter).
• Write a Java Program to create an abstract class named Shape that
contains two integers and an empty method named print Area().
Provide three classes named Rectangle, Triangle and Circle such that
each one of the classes extends the class Shape. Each one of the
classes contains only the method print Area () that prints the area of
the given shape.

Console class methods
Method Description
Reader reader() It is used to retrieve the reader object associated
with the console
String readLine() It is used to read a single line of text from the
console.
String readLine(String fmt, It provides a formatted prompt then reads the
Object... args) single line of text from the console.
char[] readPassword() It is used to read password that is not being
displayed on the console.
void flush() It is used to flushes the console.
Console class methods
Method Description
char[] readPassword(String fmt, It provides a formatted prompt then reads
Object... args) the password that is not being displayed
on the console.
Console format(String fmt, Object... It is used to write a formatted string to the
args) console output stream.
Console printf(String format, It is used to write a string to the console
Object... args) output stream.
PrintWriter writer() It is used to retrieve the PrintWriter object
associated with the console.
PrintWriter
• Java PrintWriter class is the implementation of Writer class. It is used
to print the formatted representation of objects to the text-output
stream.

Class declaration
• public class PrintWriter extends Writer
PrintWriter
Method Description
void println(boolean x) It is used to print the boolean value.
void println(char[] x) It is used to print an array of characters.
void println(int x) It is used to print an integer.
PrintWriter append(char c) It is used to append the specified character to
the writer.
PrintWriter It is used to append the specified character
append(CharSequence ch) sequence to the writer.
PrintWriter
Method Description
PrintWriter It is used to append a subsequence of specified
append(CharSequence ch, int character to the writer.
start, int end)
boolean checkError() It is used to flushes the stream and check its
error state.
protected void setError() It is used to indicate that an error occurs.
protected void clearError() It is used to clear the error state of a stream.
PrintWriter
Method Description
PrintWriter format(String It is used to write a formatted string to the
format, Object... args) writer using specified arguments and format
string.
void print(Object obj) It is used to print an object.
void flush() It is used to flushes the stream.
void close() It is used to close the stream.
Reading in Files
• Java FileInputStream class obtains input bytes from a file. It is used
for reading byte-oriented data (streams of raw bytes) such as image
data, audio, video etc.
class declaration
• public class FileInputStream extends InputStream
Reading in Files
Method Description
It is used to return the estimated number of
int available()
bytes that can be read from the input stream.
It is used to read the byte of data from the
int read()
input stream.
It is used to read up to b.length bytes of data
int read(byte[] b)
from the input stream.
It is used to read up to len bytes of data from
int read(byte[] b, int off, int len)
the input stream.
Reading in Files
Method Description
It is used to skip over and discards x bytes of data
long skip(long x)
from the input stream.
FileChannel It is used to return the unique FileChannel object
getChannel() associated with the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
It is used to ensure that the close method is call when
protected void finalize()
there is no more reference to the file input stream.
void close() It is used to closes the stream.
Writing in Files
• Java FileOutputStream is an output stream used for writing data to a
file.
• If we have to write primitive values into a file, use FileOutputStream
class.
• We can write byte-oriented as well as character-oriented data through
FileOutputStream class.
Writing in Files
Method Description
protected void finalize() It is used to clean up the connection with the
file output stream.
void write(byte[] ary) It is used to write array.length bytes from the
byte array to the file output stream.
void write(byte[] ary, int off, It is used to write len bytes from the byte array
int len) starting at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file
output stream.
Writing in Files
Method Description
FileChannel getChannel() It is used to return the file channel object
associated with the file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated
with the stream.
void close() It is used to closes the file output stream.
• Develop a Java application to generate Electricity bill. Create a class with the following members:
Consumer no., consumer name, previous month reading, current month reading, type of EB
connection (i.e domestic or commercial). Compute the bill amount using the following tariff.
• If the type of the EB connection is domestic, calculate the amount to be paid as follows:
• First 100 units - Rs. 1 per unit
• 101-200 units - Rs. 2.50 per unit
• 201 -500 units - Rs. 4 per unit
• > 501 units - Rs. 6 per unit
• If the type of the EB connection is commercial, calculate the amount to be paid as follows:
• First 100 units - Rs. 2 per unit
• 101-200 units - Rs. 4.50 per unit
• 201 -500 units - Rs. 6 per unit
• > 501 units - Rs. 7 per unit
• Develop a java application to implement currency converter (Dollar to
INR, EURO to INR, Yen to INR and vice versa), distance converter
(meter to KM, miles to KM and vice versa) , time converter (hours to
minutes, seconds and vice versa) using packages.

Develop a Java application with Employee class with Emp_name, Emp_id,
Address, Mail_id, Mobile_no as members. Inherit the classes, Programmer,
Assistant Professor, Associate Professor and Professor from employee class.
Add Basic Pay (BP) as the member of all the inherited classes with 97% of BP
as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund.
Generate pay slips for the employees with their gross and net salary.
• Write a program to perform string operations using ArrayList. Write
functions for the following
• a. Append - add at end
• b. Insert – add at particular index
• c. Search
• d. List all string starts with given letter
Thank you
Reading in console
• Java Reader is an abstract class for reading character streams. The
only methods that a subclass must implement are read(char[], int, int)
and close().
• Some of the implementation class are BufferedReader,
CharArrayReader, FilterReader, InputStreamReader, PipedReader,
StringReader.
Reading in console
Method Description
abstract void close() It closes the stream and releases any
system resources associated with it.
void mark(int readAheadLimit) It marks the present position in the
stream.
boolean markSupported() It tells whether this stream supports the
mark() operation.
int read() It reads a single character.
Reading in console
Method Description
int read() It reads a single character.
abstract int read(char[] cbuf) It reads characters into an array.
int read(char[] cbuf, int off, int len) It reads characters into a portion of an
array.
boolean read(CharBuffer target) It attempts to read characters into the
specified character buffer.
void reset() It resets the stream.
Writing in console
Method Description
append(char c) It appends the specified character to this writer.
append(CharSequence csq) It appends the specified character sequence to
this writer
append(CharSequence csq, It appends a subsequence of the specified
int start, int end) character sequence to this writer.
void close() It closes the stream, flushing it first.
void flush() It flushes the stream.
Writing in console
Method Description
write(char[] cbuf) It writes an array of characters.
write(char[] cbuf, int off, int len) It writes a portion of an array of
characters.
write(int c) It writes a single character.
write(String str) It writes a string.
write(String str, int off, int len) It writes a portion

You might also like