Oop Unit 3 - Exception Handling & Io Streams

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

UNIT - III

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

If exception matches none of handlers,


program is abandoned
22
• Java exception handling is managed by via five
keywords: try, catch, throw, throws, and finally
• Program statements to monitor are contained
within a try block
• If an exception occurs within the try block, it is
thrown
• Code within catch block catch the exception and
handle it
• System generated exceptions are automatically
thrown by the Java run-time 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
• Any code that absolutely must be executed before a
method returns is put in a finally block
• General form of an exception-handling block
try{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb){
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb){
// exception handler for ExceptionType2
}
//…
finally{
// block of code to be executed before try block ends
}
Using try and catch
• Handling an exception has two benefits,
– It allows you to fix the error
– It prevents the program from automatically terminating
• The catch clause should follow immediately the try
block
• Once an exception is thrown, program control
transfer out of the try block into the catch block
• Once the catch statement has executed, program
control continues with the next line in the program
following the entire try/catch mechanism
Output:
Division by zero.
After catch statement.

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

• When one parameter is given


a=1
Divide by 0: java.lang.ArithmeticException: / by zero
• When two parameters are given
a=2
Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException
throw
• It is possible for your program to throw an
exception explicitly
throw TrrowableInstance
• Here, TrrowableInstance must be an object of type
Throwable or a subclass Throwable
• There are two ways to obtain a Throwable objects:
– Using a parameter into a catch clause
– Creating one with the new operator
• Output:
• Caught inside demoproc.
• Recaught: java.lang.NullPointerException:
demo

• 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

• Piped streams are normally created in pairs.


• The piped output stream becomes the
underlying source for the piped input stream. For
example:
• PipedOutputStream pout = new PipedOutputStream();
• PipedInputStream pin = new PipedInputStream(pout);
PIPED – IO STREAM

• The java.io.PipedInputStream class


and java.io.PipedOutputStream class provide a
convenient means to move streaming data from
one thread to another.
• Output from one thread becomes input for the
other thread,
BUFFERED READER
import java.io.*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(r);


System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
FILTERED READER
• Java FilterReader is used to perform filtering
operation on reader stream.
• It is an abstract class for reading filtered
character streams.
• Subclasses of FilterReader should override
some of its methods and may also provide
additional methods and fields.
import java.io.*;
class CustomFilterReader extends FilterReader {
CustomFilterReader(Reader in) {
super(in);
}
public int read() throws IOException {
int x = super.read();
if ((char) x == ' ')
return ((int) '?');
else
return x;
} }
public class FilterReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("javaFile123.txt");
CustomFilterReader fr = new CustomFilterReader(reader);
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i); }
fr.close();
reader.close();
} catch (Exception e) { e.getMessage(); } } }
FILE IO STREAM CLASSES
• Java Byte streams are used to perform input and
output of 8-bit bytes, whereas Java Character
streams are used to perform input and output for
16-bit unicode.
• Though there are many classes related to character
streams but the most frequently used classes are,
FileReader and FileWriter.
• Though internally FileReader uses FileInputStream
and FileWriter uses File Output Stream but here
the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a
time.
importjava.io.*;
BYTE STREAM FILE IO
Public class CopyFile{
Public static void main(String args[]) throws IOException{
FileInputStream in= null;
FileOutputStream out= null;
try{
in= new FileInputStream("input.txt");
out= new FileOutputStream("output.txt");
Int c;
while((c= in.read()) != -1) {
out.write(c);
}
}finally{
if(in!= null) {
in.close();
}
if(out!= null) {
out.close();
importjava.io.*;
CHARACTER STREAM FILE IO
public class CopyFile{
public static void main(String args[]) throws IOException{
FileReader in= null;
FileWriter out= null;
try{
in= new FileReader("input.txt");
out= new FileWriter("output.txt");
int c;
while((c= in.read()) != -1) {
out.write(c);
}
}finally{
if(in!= null) {
in.close();
}
if(out!= null) {
out.close();
READING & WRITING
• There are three different ways for reading input
from the user in the command line
environment(console).
– 1.UsingBufferedReaderClass
– 2.UsingScannerClass
– 3.UsingConsoleClass
Using BufferedReader Class
• In Java, 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.
• BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
public class Test
{
public static void main(String[] args) throws IOException
{
//Enter data using BufferReader
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
String name= br.readLine();
System.out.println(name);
}
}
Using Scanner Class
• This is probably the most preferred method to
take input.
• The main purpose of 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 is 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.
THANK YOU..

You might also like