Oop Unit 3 - Exception Handling & Io Streams
Oop Unit 3 - Exception Handling & Io Streams
Oop Unit 3 - Exception Handling & Io Streams
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 Templates
SNO TOPIC
1 Exceptions – exception hierarchy
2 Throwing and catching exceptions
3 Built-in exceptions
4 Creating own exceptions
5 Stack Trace Elements. Input / Output Basics
6
Streams - Byte streams and Character Streams
7 Reading and Writing Console
8 Reading and Writing Files
EXCEPTION
• In Java, an exception is an event that disrupts
the normal flow of the program.
• Exception handling in java is a powerful
mechanism or technique that allows us to
handle runtime errors in a program so that the
normal flow of the program can be
maintained.
Difference between error and
exception
• Errors indicate serious problems and
abnormal conditions that most applications
should not try to handle.
• Error defines problems that are not expected
to be caught under normal circumstances by
our program.
• For example memory error, hardware error,
JVM error etc.
• Checked Exceptions
– These are the exceptions which occur during the
compile time of the program.
– The compiler checks at the compile time that
whether the program contains handlers for
checked exceptions or not.
• NoSuchFieldException
• InstantiationException
• IllegalAccessException
• ClassNotFoundException
• NoSuchMethodException
• CloneNotSupportedException
• InterruptedException
• Unchecked Exceptions
– Unchecked exceptions are the exceptions which occur
during the runtime of the program.
– These exceptions cannot be anticipated and recovered
like programming bugs, such as logic errors or improper
use of an API.
– These type of exceptions are also called Runtime
exceptions that are usually caused by data errors, like
arithmetic overflow, divide by zero etc.
• Here is the list of unchecked exceptions.
–IndexOutOfBoundsException
–ArrayIndexOutOfBoundsException
–ClassCastException
–ArithmeticException
–NullPointerException
–IllegalStateException
–SecurityException
• Error
–The errors in java are external to the
application.
–An Error indicates serious problems that a
reasonable application should not try to
catch.
–Most such errors are abnormal conditions.
Exception Hierarchy
• Checked Exceptions
– These are the exceptions which occur during the
compile time of the program.
– The compiler checks at the compile time that
whether the program contains handlers for
checked exceptions or not.
• NoSuchFieldException
• InstantiationException
• IllegalAccessException
• ClassNotFoundException
• NoSuchMethodException
• CloneNotSupportedException
• InterruptedException
• Unchecked Exceptions
– Unchecked exceptions are the exceptions which occur
during the runtime of the program.
– These exceptions cannot be anticipated and recovered
like programming bugs, such as logic errors or improper
use of an API.
– These type of exceptions are also called Runtime
exceptions that are usually caused by data errors, like
arithmetic overflow, divide by zero etc.
• Here is the list of unchecked exceptions.
–IndexOutOfBoundsException
–ArrayIndexOutOfBoundsException
–ClassCastException
–ArithmeticException
–NullPointerException
–IllegalStateException
–SecurityException
• Error
–The errors in java are external to the
application.
–An Error indicates serious problems that a
reasonable application should not try to
catch.
–Most such errors are abnormal conditions.
• Exception
– Indication of problem during execution
• Uses of exception handling
– Process exceptions from program components
– Handle exceptions in a uniform manner in large projects
– Remove error-handling code from “main line” of
execution
• A method detects an error and throws an exception
– Exception handler processes the error
– Uncaught exceptions yield adverse effects
• Might terminate program execution
Exception Handler
Exception
"thrown" here
Thrown exception matched against
first set of exception handlers
Exception
handler
If it fails to match, it is matched against
next set of handlers, etc.
Exception
handler
26
• A try and catch statement form a unit.
• The scope of the catch clause is restricted
to those statements specified by the
immediately preceding try statement
• You cannot use try on a single statement
• Multiple catch Clauses:
– If more than one error can occur, then we use multiple
catch clauses
– 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
• If no command line argument is provided, then you
will see the following output:
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks
• If any command line argument is provided, then
you will see the following output:
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
Nested try Statements
• 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,
then the next try statement’s catch handlers are
inspected for a match
• If a method call within a try block has try block
within it, then then it is still nested try
• When no parameter is given:
Divide by 0: java.lang.ArithmeticException: / by zero
• Output:
– Caught inside demoproc.
– Recaught: java.lang.NullPointerException: demo
throws
• If a method is capable of causing an exception
that it does not handle, it must specify this
behavior so that callers of the method can
guard themselves against that exception
type method-name parameter-list) throws exception-list
{
// body of method
}
• It is not applicable for Error or RuntimeException, or
any of their subclasses
Output:
Inside throwOne.
Caught java.lang.IllegalAccessException: demo
finally
• It is used to handle premature execution of a
method (i.e. a method open a file upon entry
and closes it upon exit)
• finally creates a block of code that will be
executed after try/catch block has completed
and before the code following the try/catch
block
• finally clause will execute whether or not an
exception is thrown
User-Defined Exceptions
• Sometimes, the built-in exceptions in Java are
not able to describe a certain situation. In
such cases, user can also create exceptions
which are called ‘user-defined Exceptions’.
class MyOwnException extends Exception
{ public MyOwnException(String msg) { super(msg);
}
}
class EmployeeTest
{
static void employeeAge(int age) throws MyOwnException {
if(age < 0)
throw new MyOwnException("Age can't be less than zero"); else
System.out.println("Input is valid!!");
}
public static void main(String[] args)
{
try { employeeAge(-2);
}
catch (MyOwnException e)
{
e.printStackTrace();
}
}
}
IO - BASICS
• 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.
IO - STREAMS
• 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.
IO - STREAMS
• Output Stream
– Java application uses an output stream to write
data to a destination; it may be a file, an array,
peripheral device or socket.
• Input Stream
– Java application uses an input stream to read data
from a source; it may be a file, an array, peripheral
device or socket.
IO - STREAMS
IO - BASICS
• In Java, 3 streams are created for us
automatically. All these streams are attached
with the console.
• 1) System.out: standard output stream
• 2) System.in: standard input stream
• 3) System.err: standard error stream
IO - STREAM IN JAVA
IO - STREAM IN JAVA
IO – BYTE STREAM CLASSES
BYTE STREAM CLASSES
• In java, the byte stream is an 8 bits carrier. The
byte stream in java allows us to transmit 8 bits
of data.
• In Java 1.0 version all IO operations were byte
oriented, there was no other stream (character
stream).
• The java byte stream is defined by two abstract
classes, InputStream and OutputStream.
• The Input Stream and Output Stream classes
have several concrete classes to perform various
IO operations based on the byte stream
BYTE STREAM CLASSES
INPUT - STREAM METHODS
OUTPUT - STREAM METHODS
CHARACTER STREAM CLASSES
• The java character stream is defined by two
abstract classes, Reader and Writer.
• The Reader class used for character stream
based input operations, and the Writer class
used for character stream based output
operations.
• The Reader and Writer classes have several
concrete classes to perform various IO
operations based on the character stream.
CHARACTER STREAM CLASSES
PIPED – IO CLASSES
PIPED – IO STREAM