[go: up one dir, main page]

0% found this document useful (0 votes)
21 views93 pages

EXPHNDL

Uploaded by

Sahitee Basani
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)
21 views93 pages

EXPHNDL

Uploaded by

Sahitee Basani
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/ 93

 The Exception Handling in Java is one of

the powerful mechanism to handle the


runtime errors so that normal flow of the
application can be maintained.
 we will learn about Java exceptions, its
type and the difference between
checked and unchecked exceptions.
 Dictionary Meaning: Exception is an
abnormal condition.
 The core advantage of exception
handling is to maintain the normal flow of
the application.
 Suppose there are 10 statements in your
program and there occurs an exception
at statement 5, the rest of the code will
not be executed i.e. statement 6 to 10
will not be executed.
 If we perform exception handling, the
rest of the statement will be executed.
That is why we use exception handling
in Java.
 Checked Exception
 Unchecked Exception
 Error
1) Checked Exception
The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions
e.g. IOException, SQLException etc
Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes which inherit RuntimeException are known as
unchecked exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they
are checked at runtime.

3) Error
Error is irrecoverable
e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
In the above example, 100/0 raises an ArithmeticException which is
handled by a try-catch block.
 Exception handling allows us to control the
normal flow of the program by using
exception handling in program.
 It throws an exception whenever a calling
method encounters an error providing that
the calling method takes care of that error.
 It also gives us the scope of organizing and
differentiating between different error types
using a separate block of codes. This is
done with the help of try-catch blocks
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());//NullPointerEx
ception
3) A scenario where NumberFormatException
occurs
The wrong formatting of any value
may occur NumberFormatException.
Suppose I have a string variable that has
characters, converting this variable into
digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatExcep
tion
4) A scenario where
ArrayIndexOutOfBoundsException
occurs
If you are inserting any value in the wrong
index, it would result in
ArrayIndexOutOfBoundsException as
shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsExcepti
on
Output:
java.lang.ArithmeticException: / by zero rest of the code
 The JVM firstly checks whether the
exception is handled or not.
 If exception is not handled, JVM provides a
default exception handler that performs the
following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods
where the exception occurred).
 Causes the program to terminate.
 But if exception is handled by the
application programmer, normal flow of the
application is maintained i.e. rest of the
code is executed.
 This small program includes an expression that
intentionally causes a divide-by-zero error:
class Exc0 {
public static void main(String args[]) {
int d = 0; int a = 42 / d; } }
When the Java run-time system detects the
attempt to divide by zero, it constructs a new
exception object and then throws this exception.
This causes the execution of Exc0 to stop,
because once an exception has been thrown, it must
be caught by an exception handler and dealt with
immediately
 Stack Trace is a list of method calls from the
point when the application was started to the
point where the exception was thrown. The
most recent method calls are at the top.
 A stack trace is a very helpful debugging tool.
It is a list of the method calls that the
application was in the middle of when an
Exception was thrown.
 This is very useful because it doesn't only show
you where the error happened, but also how
the program ended up in that place of the
code.
 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.
 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.
Arithmetic Exception occurs
rest of the code
 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 ArithmeticException must come
before catch for Exception
 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
 The try block within a try block is known
as nested try block in java.
 Why use nested try block
 Sometimes a situation may arise where a
part of a block may cause one error and
the entire block itself may cause another
error. In such cases, exception handlers
have to be nested.
 Java finally block is a block that is
used to execute important code such as
closing connection, stream etc.
 Java finally block is always executed
whether exception is handled or not.
 Java finally block follows try or catch
block.
 For each try block there can be zero or
more catch blocks, but only one finally
block.
 The finally block will not be executed if
program exits(either by calling
System.exit() or by causing a fatal error
that causes the process to abort).
 The Java throws keyword is used to declare
an exception. It gives an information to the
programmer that there may occur an
exception so it is better for the programmer
to provide the exception handling code so
that normal flow can be maintained.
 Exception Handling is mainly used to handle
the checked exceptions. If there occurs
any unchecked exception such as
NullPointerException, it is programmers fault
that he is not performing check up before
the code being used.
Syntax of java throws
return_type method_name() throws except
ion_class_name{
//method code
}
unchecked Exception: under your control
so correct your code.
error: beyond your control e.g. you are
unable to do anything if there occurs
VirtualMachineError or
StackOverflowError
 Now Checked Exception can be
propagated (forwarded in call stack).
 It provides information to the caller of the
method about the exception
 Java I/O (Input and Output) is used to
process the input and produce the
output based on the input.
 Java uses the concept of stream to
make I/O operation fast.
 The java.io package contains all the
classes required for input and output
operations.
 Java I/O (Input and Output) is used to
process the input and produce the output.
 Java uses the concept of stream to make
I/O operation fast. All the classes required
for input and output operations are
declared in java.io package.
 A stream can be defined as a sequence of
data. The Input Stream is used to read data
from a source and the OutputStream is
used for writing data to a destination.
 A stream can be defined as a sequence
of data. there are two kinds of Streams
 InputStream: The InputStream is used to
read data from a source.
 OutputStream: the OutputStream is used
for writing data to a destination.
 Java byte streams are used to perform
input and output of 8-bit bytes
 FileInputStream
 FileOutputStream.
Character Streams
 Java Character streams are used to
perform input and output for 16-bit
unicode.
 FileReader ,
 FileWriter
 InputStream class is an abstract class. It is
the super class of all classes representing an
input stream of bytes.
 The Input Strearn class is the superclass for
all byte-oriented input stream classes.
 All the methods of this class throw an
IOException.
 Being an abstract class, the InputStrearn
class cannot be instantiated hence, its
subclasses are used
 OutputStream class is an abstract class. It
is the super class of all classes
representing an output stream of bytes.
An output stream accepts output bytes
and sends them to some sink.
 The character stream classes are also
topped by two abstract classes
 Reader and Writer.
 Reader classes are used to read 16-bit
unicode characters from the input
stream.
 The Reader class is the superclass for all
character-oriented input stream classes.
 All the methods of this class throw an IO
Exception.
 Being an abstract class, the Reader
class cannot be instantiated hence its
subclasses are used
int read()
returns the integral representation of the next available characterof
input. It returns -1 when end of file is encountered
int read (char buffer [])
attempts to read buffer. length characters into the buffer and
returns the total number of characters successfully read. It returns
-I when end of file is encountered
void close ()
closes the input source. If an attempt is made to read even
after closing the stream then it generates IOException
 Writer classes are used to write 16-bit
Unicode characters onto an outputstream.
 The Writer class is the superclass for all
character-oriented output stream classes .
 All the methods of this class throw an
IOException.
 Being an abstract class, the Writer class
cannot be instantiated hence, its
subclasses are used
void write ()
writes data to the output stream
void write (int i)
Writes a single character to the output stream
void write (char buffer [] )
writes an array of characters to the output stream
void flush ()
flushes the output stream and writes the waiting
buffered output characters
Standard Input:
This is used to feed the data to user's
program and usually a keyboard is used as
standard input stream and represented as
System.in.
Standard Output:
This is used to output the data
produced by the user's program and
usually a computer screen is used to
standard output stream and represented as
System.out.
 This is used to output the error data
produced by the user's program and
usually a computer screen is used to
standard error stream and represented
as System.err.
 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.
String text=System.console().readLine();
System.out.println("Text is: "+text);
Java Console class declaration
Let's see the declaration for
Java.io.Console class:
public final class Console extends Object i
mplements Flushable
 It is an abstract class for writing to
character streams. The methods that a
subclass must implement are
write(char[], int, int), flush(), and close().
 Most subclasses will override some of the
methods defined here to provide higher
efficiency, functionality or both.
Output:
Done

output.txt
I love my country
 Java Reader is an abstract class for reading
character streams. The only methods that a
subclass must implement are read(char[],
int, int) and close().
 Most subclasses, however,
will override some of the methods to
provide higher efficiency, additional
functionality, or both.

 implementation class are BufferedReader,


CharArrayReader, FilterReader, InputStream
Reader, PipedReader, StringReader
file.txt:
I love my country

Output:
I love my country
 Java FileWriter class is used to write
character-oriented data to a file. It is
character-oriented class which is used
for file handling in java.
 Unlike FileOutputStream class, you don't
need to convert string into
byte array because it provides method
to write string directly
public class FileWriter extends OutputStreamWriter

Constructor Description

FileWriter(String file) Creates a new file. It gets file


name in string.
FileWriter(File file) Creates a new file. It gets file
name in File object.
Welcome to javaTpoint.
 Java FileReader class is used to read
data from the file. It returns data in byte
format like FileInputStream class.
 It is character-oriented class which is
used for file handling in java.
Java FileReader class declaration
public class FileReader extends InputStrea
mReader
Output:
Welcome to javaTpoint.
 Java BufferedWriter class is used to
provide buffering for Writer instances. It
makes the performance fast. It
inherits Writer class.
 The buffering characters are used for
providing the efficient writing of
single arrays, characters, and strings.
Class declaration
public class BufferedWriter extends Writer
 Java BufferedReader class is used to
read the text from a character-based
input stream.
 It can be used to read data line by line
by readLine() method. It makes the
performance fast. It inherits Reader class.
Java BufferedReader class declaration
public class BufferedReader extends Read
er
Output:
Enter your name
Nakul Jain
Welcome Nakul Jain

You might also like