0% found this document useful (0 votes)
20 views33 pages

Unit 3 - Study Material Oops

Uploaded by

crrmsa2020
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)
20 views33 pages

Unit 3 - Study Material Oops

Uploaded by

crrmsa2020
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/ 33

Unit 3

EXCEPTION HANDLING AND I/O

Exceptions - exception hierarchy - throwing and catching exceptions – built-in exceptions,


creating own exceptions, Stack Trace Elements. Input / Output Basics – Streams – Byte
streams and Character streams – Reading and Writing Console – Reading and Writing Files
Exceptions
• An exception is an abnormal condition that arises in a code sequence
at run time.
• 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.
• 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
Exceptions (Cont..)
• Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.
• Program statements that you want to monitor for exceptions are
contained within a try block. If an exception occurs within the try
block, it is thrown. Your code can catch this exception (using catch)
and handle it in some rational manner. System-generated exceptions
are automatically thrown by the Java runtime system.
• To manually throw an exception, use the keyword throw.
• Any exception that is thrown out of a method must be specified as
such by a throws clause.
Exceptions (Cont..)
• Any code that absolutely must be executed after a try block
completes is put in a finally block.
• Any exception that is not caught by your program will ultimately be
processed by the default handler.
Checked Exceptions in Java

• These are the exceptions that are checked at compile time.


• If some code within a method throws a checked exception, then the
method must either handle the exception or it must specify the
exception using the throws keyword.
• In checked exceptions, there are two types: fully checked and
partially checked exceptions.
• A fully checked exception is a checked exception where all its child
classes are also checked, like IOException, and InterruptedException.
A partially checked exception is a checked exception where some of
its child classes are unchecked, like an Exception.
Unchecked Exceptions in Java

• These are the exceptions that are not checked at compile time. In
C++, all exceptions are unchecked, so it is not forced by the compiler’s
to either handle or specify the exception.
• In Java, exceptions under Error and RuntimeException classes are
unchecked exceptions.
Built-in Exception

• Exceptions that are already available in Java libraries are referred to as


built-in exception. These exceptions are able to define the error
situation so that we can understand the reason of getting this error.
User-Defined Exceptions

• Sometimes, the built-in exceptions in Java are not able to describe a


certain situation. In such cases, the user can also create exceptions
which are called ‘user-defined Exceptions’.
• The user should create an exception class as a subclass of the
Exception class. Since all the exceptions are subclasses of the
Exception class, the user should also make his class a subclass of it.
This is done as:
class MyException extends Exception
Stack Trace Elements
• Stack trace is nothing but location of the exceptions.
• It traces the locations where exception raised.
• In Java, the stack trace is an array of stack frames.
• It is also known as stack backtrace (or backtrace).
• The stack frames represent the movement of an application during
the execution of the program.
Stack Trace Elements (Cont..)
• It collects the information of all the methods that are invoked by a
program.
• When we do not care about the unhandled exceptions and the
program throws the exceptions then Java stack trace prints the stack
trace on the console by default.
• The JVM automatically produces the stack trace when an exception is
thrown. In stack trace, each element represents a method invocation.
Stack Trace Elements (Cont..)
Stack Trace Elements
• The StackTraceElement class provides a constructor that parses four
parameters as an argument and creates a stack trace element that denotes
the specified execution point.
• public StackTraceElement(String declaringClass, String methodName, Strin
g fileName, int lineNumber)
declaringClass: the qualified name of the class that contains the execution point.
methodName: It represents the method name that contains the execution point.
fileName: It represents the file name that contains the execution point.
lineNumber: It represents the line number of the source of the execution point.
It throws the NullPointerException if the
parameters declaringClass and methodName are null.
Input in Java
• Buffered Reader Class
• Using Scanner Class
• Using Console Class
• Command Line Argument
Scanner Class in Java
• To create an object of the Scanner class in java, you need to pass
System.in in the constructor of the Scanner class. System is a class in
Java and in is a static variable of type InputStream .

Object

inherits

Scanner
Different methods in Scanner Class
Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads an int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user


BufferedReader
• The BufferedReader class of the java.io package can be used
with other readers to read data (in characters) more efficiently.

• It extends the abstract class Reader.

• The BufferedReader maintains an internal buffer of 8192 characters.

• During the read operation in BufferedReader, a chunk of characters is


read from the disk and stored in the internal buffer. And from the internal
buffer characters are read individually.

• Hence, the number of communication to the disk is reduced.


• This is why reading characters is faster using BufferedReader.
BufferedReader Constructor

BufferedReader(Reader rd) It is used to create a buffered character input


stream that uses the default size for an input buffer.
BufferedReader(Reader rd, int size) It is used to create a buffered character input
stream that uses the specified size for an input
buffer.
Different methods in BufferedReader class
Method Description
int read() It is used for reading a single character.
int read(char[] cbuf, int off, int len) It is used for reading characters into a portion of
an array.
boolean markSupported() It is used to test the input stream support for the mark
and reset method.
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is ready to be
read.
long skip(long n) It is used for skipping the characters.
void reset() It repositions the stream at a position the mark method
was last called on this input stream.

void mark(int readAheadLimit) It is used for marking the present position in a stream.

void close() It closes the input stream and releases any of the system
resources associated with the stream.
Command Line Arguments in java
Console class in Java
• The Java Console class is be used to get input from console. It
provides methods to read texts and passwords.

• If you read password using Console class, it will not be displayed to


the user.

• The java.io.Console class is attached with system console internally.


The Console class is introduced since JDK 1.5.
FileInputStream Class Methods
Output Streams
• FileOutputStream.
• ByteArrayOutputStream.
• ObjectOutputStream.
FileOutputStream
• FileOutputStream is an outputstream for writing data/streams of raw
bytes to file or storing data to file. FileOutputStream is a subclass of
OutputStream.
• FileOutputStream(File file): Creates a file output stream to write to
the file represented by the specified File object.

public class FileOutputStream extends OutputStream


ByteArrayOutputStream.

• Java ByteArrayOutputStream class is used to write common data into


multiple files. In this stream, the data is written into a byte array
which can be written to multiple streams later.
Constructor Description
ByteArrayOutputStream() • Creates a new byte array
output stream with the initial capacity of
32 bytes, though its size increases if
necessary.
ByteArrayOutputStream(int size) • Creates a new byte array output stream,
with a buffer capacity of the specified
size, in bytes.
ObjectOutputStream

• The ObjectOutputStream class provides implementations for different


methods present in the OutputStream class.
Syntax:
FileOutputStream file = new FileOutputStream("file.txt");
// Creates an ObjectOutputStream
ObjectOutputStream output = new ObjectOutputStream(file);
Java DataInputStream Class

• Java DataInputStream class allows an application to read primitive


data from the input stream in a machine-independent way.

• Java application generally uses the data output stream to write data
that can later be read by a data input stream.

Syntax
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
Character Streams

• The Java platform stores character values using Unicode conventions.


• Character stream I/O automatically translates this internal format to
and from the local character set.
• A program that uses character streams in place of byte streams
automatically adapts to the local character set and is ready for
internationalization — all without extra effort by the programmer.
Character Streams Code Snippet
FileReader inputStream = null; FileWriter outputStream = null;
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c); }
if (inputStream != null) {
inputStream.close();}

if (outputStream != null) {
outputStream.close();
}
File Output Stream
• FileOutputStream is an output stream for writing data to a File or to a
FileDescriptor.
Syntax

String path = "C:\\users\\data\\datafile.txt";

FileOutputStream output = new FileOutputStream(path);


FileOutputStream class methods

You might also like