unit3newLMS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

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.
Exception Hierarchy
• All exception types are subclasses of the built-in class Throwable.
• Immediately below Throwable are two subclasses that partition exceptions into two distinct branches.
• One branch is headed by Exception. This class is used for exceptional conditions that user programs should
catch.
• The other branch is topped by Error, which defines exceptions that are not expected to be caught under
normal circumstances by your program.

Throwable

Exception Error

RuntimeException
Uncaught Exception
• 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.
Using try and catch
• 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, include a catch clause that specifies the
exception type that you wish to catch.
Multiple catch Clauses
• In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses, each
catching a different type of exception.
• When an exception is thrown, each catch statement is inspected in order, and the
first one whose type matches that of the exception is executed.
• After one catch statement executes, the others are bypassed, and execution
continues after the try /catch block.
Nested try Statements
• The try statement can be nested. That is, a try statement can be inside the block
of another try.
• Each time a try statement is entered, the context of that exception is pushed on
the stack.
• If an inner try statement does not have a catch handler for a particular
exception, the stack is unwound and the next try statement’s catch handlers are
inspected for a match.
• This continues until one of the catch statements succeeds, or until all of the
nested try statements are exhausted.
• If no catch statement matches, then the Java run-time system will handle the
exception.
Using throw
• The program can throw an exception explicitly, using the throw statement.
• The general form of throw is throw ThrowableInstance;
• Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
• Primitive types, such as int or char, as well as non-Throwable classes, such as String and
Object, cannot be used as exception
• There are two ways you can obtain a Throwable object: using a parameter in a catch
clause or creating one with the new operator.
• The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed.
• The nearest enclosing try block is inspected to see if it has a catch statement that
matches the type of exception.
Using throws
• If a method causes an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that
exception.
• A throws clause lists the types of exceptions that a method might throw.
• This is necessary for all exceptions, except those of type Error or
RuntimeException, or any of their subclasses.
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Using finally
• 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.
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 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, Stri
ng 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.
I/O Basics
• Java programs perform I/O through streams.
• 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.
• All streams behave in the same manner, even if the actual physical
devices to which they are linked differ.
• Thus, the same I/O classes and methods can be applied to any type of
device.
Input Stream and Output Stream
• Input stream can abstract 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.
• Streams are a clean way to deal with input/output without having
every part of your code understand the difference between a
keyboard and a network.
• Java implements streams within class hierarchies defined in the
java.io package.
Byte Streams and Character Streams
• 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.
• Character streams provide a convenient means for handling input and
output of characters.
The Byte Stream Classes
• Byte streams are defined by using two class hierarchies. At the top are
two abstract classes: InputStream and OutputStream.
• The abstract classes InputStream and OutputStream define several
key methods that the other stream classes implement.
• Two of the most important are read( ) and write( ),which,
respectively, read and write bytes of data. Each has forms that are
abstract and must be overridden by derived stream classes.
The Byte Stream Classes in java.io
The Character Stream I/O Classes in java.io
The Predefined Streams
• Java programs automatically import the java.lang package.
• This package defines a class called System, which encapsulates
several aspects of the run-time environment.
• System also contains three predefined stream variables: in, out, and err.
• System.out refers to the standard output stream.
• System.in refers to standard input, which is the keyboard by default.
• System.err refers to the standard error stream, which also is the
console by default.
Reading Console Input
• Console input is accomplished by reading from System.in. To obtain a character
based stream that is attached to the console, wrap System.in in a
BufferedReader object.
• BufferedReader supports a buffered input stream. A commonly used constructor
is shown here:
BufferedReader(Reader inputReader)
• Reader is an abstract class. One of its concrete subclasses is InputStreamReader,
which converts bytes to characters. To obtain an InputStreamReader object that
is linked to System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
Reading Console Input (Cont..)
• BufferedReader br = new BufferedReader(new
• InputStreamReader(System.in));
• After this statement executes, br is a character-based stream that is linked to the
console through System.in.
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.
Reading Files
• Two of the most often-used stream classes are FileInputStream and
FileOutputStream, which create byte streams linked to files.
• To open a file, you simply create an object of one of these classes, specifying the
name of the file as an argument to the constructor.
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
To read from a file, you can use a version of read( ) that is defined within FileInputStream.
int read( ) throws IOException
• Each time that it is called, it reads a single byte from the file and returns the byte
as an integer value.
• read( ) returns –1 when the end of the file is encountered. It can throw an
IOException.
Writing Console Output
• Console output is most easily accomplished with print( ) and println( ).These
methods are defined by the class PrintStream which is the type of object
referenced by System.out.
• PrintStream is an output stream derived from OutputStream, it also implements
the low-level method write( ).
void write(int byteval)
This method writes the byte specified by byteval.
PrintWriter Class
• The recommended method of writing to the console when using Java is through a
PrintWriter stream.
• PrintWriter is one of the character-based classes.
• Using a character-based class for console output makes internationalizing your
program easier.
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
• Here, outputStream is an object of type OutputStream, and flushOnNewline
controls whether
• Java flushes the output stream every time a println( ) method is called. If
flushOnNewline is true, flushing automatically takes place. If false, flushing is not
automatic.
Automatically Closing a File
• JDK 7 adds a new feature that offers another way to manage resources, such as file
streams, by automating the closing process.
• This feature is called as automatic resource management, or ARM for short.
• Automatic resource management is based on an expanded form of the try statement.
try (resource-specification) {
// use the resource
}
• Here, resource-specification is a statement that declares and initializes a resource, such
as a file stream.
• It consists of a variable declaration in which the variable is initialized with a reference to
the object being managed. When the try block ends, the resource is automatically
released.

You might also like