Unit 3

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

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
The Exception Handling in Java is one of the powerful mechanism
to handle the runtime errors so that the normal flow of the
application can be maintained.

An exception is an unwanted or unexpected event, which occurs


during the execution of a program i.e at run time, that disrupts
the normal flow of the program’s instructions.

 E.g.,
 A user has entered invalid data.
 A file that needs to be opened cannot be found
Advantage of Exception Handling
• core advantage of exception handling is to maintain the normal
flow of the application
• exception normally disrupts the normal flow of the application
that is why we use exception handling
statement 1;  
statement 2;  
statement 3; 
statement 4;  
statement 5;//exception occurs  
statement 6;  
statement 7;  
statement 8;  

By handling we make sure that all the statements execute and the
flow of program doesn’t break.
EXCEPTIONS - an abnormal condition

Exception types /Exception Hierarchy


 All exception types are subclasses of the built-in class Throwable
 There are two subclasses that partition exception into two distinct branches.
 They are: (i) Exception (ii) Error
Exception Class
 is used for exceptional conditions that user programs should catch and
handle.
 All user-defined exception / custom exception must be subclass of
Exception Class
 java.lang package defines several exception classes
 Exceptions are broadly classified as 'checked exceptions' and 'unchecked
exceptions
Error(serious problem)
 These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer
 exceptions that are not expected to be caught under normal circumstances by the
program.
 Exceptions of type Error are used by the Java run-time system
 Such a error are: stack overflow, memory out of range, system crash, network
failure, etc
Unchecked Exceptions
 The exceptions that are not checked at compile time are called unchecked
exceptions.
 These type of exception need not be included in the program
 Classes that extends RuntimeException comes under unchecked exceptions.
 responsibility of the programmer to handle these exceptions and provide a safe exit
 Examples for unchecked exceptions ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundException.
Checked Exceptions
 Exceptions that are checked at compile-time are called checked exceptions
 all classes that extends Exception class except UncheckedException comes under
checked exception category.
 These Exception must be included in the method signature
 Example for Checked Exception are FileNotFoundException,
ClassNotFoundException, CloneNotSupportedException
Java Exception Keywords

Keyword Description
The "try" keyword is used to specify a block where we should place
try an exception code. It means we can't use try block alone. The try
block must be followed by either catch or finally.

The "catch" block is used to handle the exception. It must be


catch preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.

The "finally" block is used to execute the necessary code of the


finally program. It is executed whether an exception is handled or not.

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

The "throws" keyword is used to declare exceptions. It specifies


throws that there may occur an exception in the method. It doesn't throw
an exception. It is always used with method signature.
Using try catch with finally and multiple catch statements : general form
try {
// block of code to monitor for an error
}
catch(ExceptionType1 ob1) {
// exception handling code here
}
catch(ExceptionType2 ob2) {
// exception handling code here
}

finally {
// code placed here will always executed
}
try block - program statements that want to monitor for exception

catch block - immediately followed by try block, there can be one or more
catch block, one block for each exception types that excepted to occur in the try
block.
When exception occurs in try block, control is transferred to corresponding
catch block that match with an exception thrown

finally block – The code in the finally block always get executed, regardless of
whether error occurred in the try block or not.
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException  
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;  
System.out.println(s.length());//NullPointerException  
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters; converting this
variable into digit will cause NumberFormatException.
String s="abc";  
int i=Integer.parseInt(s);//NumberFormatException  

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
int a[]=new int[5];  
a[10]=50; //ArrayIndexOutOfBoundsException  
Displaying description of an exception
To print description of an exception, pass exception object as argument to
println() statement.

 Whenever exception object passed to println, it calls toString ( ) method to


print the reason of the exception.
 To display only reason for the exception use getMessage() method
 System.out.println("reason: ” +a.getMessage()); //Output : reason : 4
Java Multi-catch block
A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform
different tasks at the occurrence of different exceptions, use java multi-
catch block.
• At a time only one
exception occurs and at
a time only one catch
block is executed.

• All catch blocks must


be ordered from most
specific to most general,
i.e. catch for Arithmetic
Exception must come
before catch for
Exception.
Nested try block

1. In Java, using a try block inside another try block is permitted.


2. It is called as nested try block.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while
the outer try block can handle
the ArithemeticException (division by zero).
Syntax:
....    
//main try block  
try    
{    
    statement 1;    
    statement 2;    
//try catch block within another try block  
    try    
    {    
        statement 3;    
        statement 4;    
//try catch block within nested try block  
        try    
Nested try block
        {    
            statement 5;    
            statement 6;    
     }    
Click to add text
        catch(Exception e2)    
        {    
//exception message  
        }    
  
    }    
    catch(Exception e1)    
    {    
//exception message  
    }    
}    
//catch block of parent (outer) try block  
catch(Exception e3)    
{    
//exception message  
}    
Java finally block
Java finally block is always executed whether an exception is
handled or not. Therefore, it contains all the necessary
statements that need to be printed regardless of the exception
occurs or not.

Case 1: When an exception does not occur

Case 2: When an exception occur


but not handled by the catch block

Case 3: When an exception occurs


and is handled by the catch block
throw clause Java throw Exception
 to generate an exception explicitly
 Syntax : throw thowrableInstance; => thowrableInstance must be an object of type
Throwable or subclass of Throwable
 Throwable object can be obtain in two way
 create one with new operator
 using parameter caught into catch block
 flow of exception stops immediately after the throw statement, any subsequent
statement will not all not execute.
Java Throws Keyword

1. Throws keyword is used when callee doesn’t want to


handle the exception rather it wants to extend this
responsibility of handling the exception to the caller of
the function.
2. Basically says what sort of exception the code can
throw and relies on the caller to handle it.
3. It is used to handle checked Exceptions as the compiler
will not allow code to compile until they are handled.
Throw Throws
This keyword is used to This keyword is used to declare
explicitly throw an exception. an exception.
A checked exception cannot be A checked exception can be
propagated with throw only. propagated with throws.
The throw is followed by an Throws are followed by class
instance and used with a and used with the method
method signature.
You cannot throw multiple You can declare multiple
exceptions. exceptions
Java Custom/ Userdefined Exception

You can create your own exception and give implementation as


to how it should behave. Your exception will behave like a child’s
class of Exception.

Syntax:
class YourException extends Exception{}
Example:
1. let’s say, you are working with an airline company 
2. You are in the luggage check-in department and as per rules, you can
allow 15kg per customer.
3. So now more than 15kg of weight is an abnormal condition for us or in
other words its an exception
4. This is our logic-based exception, so we’ll create our custom exception
WeightLimitExceeded 
5. As per syntax, it will extend Exception.
6. We define the constructor which will get invoked as soon as an
exception will be thrown
7. We have to explicitly throw the exception and hence we will use throw
keyword for that.
8. Using throws keyword is as per our need. If we are handling an
exception where it is getting thrown then we can avoid throws, else we
will use throws and handle it in the caller.
Java Unchecked Exceptions: RuntimeException Subclasses defined in java.lang:

Exception Meaning
Arithmetic error, such as divide-by-
ArithmeticException
zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds
Assignment to an array element of an
ArrayStoreException
incompatible type
ClassCastException Invalid cast
Illegal argument used to invoke a
IllegalArgumentException
method
NegativeArraySizeException Array created with a negative size
NullPointerException Invalid use of a null reference
Invalid conversion of a string to a
NumberFormatException
numeric format
Attempt to index outside the bounds
StringIndexOutOfBounds
of a string
TypeNotPresentException Type not found
Java Checked Exceptions :defined in java.lang

Exception Meaning
ClassNotFoundException Class not found
Attempt to clone an object that doesn't
CloneNotSupportedException
implement the Cloneable interface
IllegalAccessException Access to a class is denied
Attempt to create an object of an
InstantiationException
abstract class or interface
One thread has been interrupted by
InterruptedException
another thread
Input / Output 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.
 A stream(logical entity) is an abstraction that either produces or consumes
information.
 A stream is linked to a physical device by the Java I/O system
 An input stream can read many 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
Byte Streams and Character Streams

• Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.

• 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 FileOutputStream but here the major
difference is that FileReader reads two bytes at a time and FileWriter
writes two bytes at a time.
Byte Streams and Character Streams
2. Character Stream
 Handles input and output of characters(used to read and write a single
character of data.)
 use Unicode and, therefore, can be internationalized.
 added by Java 1.1
Byte Stream Classes
 are defined by using two class hierarchies

These two abstract classes have several concrete classes that handle various
devices such as disk files, network connection etc.
Throws IOException
Byte Streams classes
 Some important Byte stream classes
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard
datatype
DataOutputStream An output stream that contain method for
writing java standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println()
method
These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data.
Character Stream Classes
Uses two abstract class at the top of hierarchy, they are Reader and Writer.
two abstract classes have concrete classes that handle unicode character
Some important Byte stream classes
Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream ou

These classes define several key methods. Two most important are
1.read() : reads characters of data.
2.write() : Writes characters of data.
Click to add text
STACK TRACE ELEMENTS

 A stack trace (also called stack backtrace or stack traceback), is a list


of stack frames.
 A stack frame is information about a method or function that your
code called(the name of the method, the name of file and the source
code line number.)
Defn-1: Java stack trace is a list of frames that starts at the current
method and extends to when the program started.
or
Defn-2: A stack trace provides information on the execution history and
lists the names of the classes and methods that were called at the point
when the exception occurred
 Stack trace listings are displayed whenever a java program terminates
with an uncaught exception
 StackTraceElement class
 StackTraceElement has one constructor:
StackTraceElement(String className, String methName, string fileName, int
line)
 An array of StackTraceElements is returned by the getStackTrace( ) method
of the Throwable class
 The StackTraceEleement class has methods to obtain the file name , line
number ,class name and method name of the executing line of code
Method Description

String getClassName( ) Returns the class name of the execution point


described by the invoking StackTraceElement.
String getFileName( ) Returns the filename of the execution point
described by the invoking StackTraceElement.
int getLineNumber( ) Returns the source-code line number of the
execution point described by the invoking
StackTraceElement. In some situations, the line
number will not be available, in which case a
negative value is returned.

String getMethodName( ) Returns the method name of the execution point


described by the invoking StackTraceElement.

You might also like