Professional Documents
Culture Documents
Unit 3
Unit 3
Unit 3
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
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.
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
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.
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