Chapter 09 - Exception Handling
Chapter 09 - Exception Handling
1
Exception Handling
What is Exception Handling?
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.
An exception normally disturbs the normal flow of the application that is why
we use exception handling.
What is an Exception?
An exception (or exceptional event) is a problem that arises during the
execution of a program.
When an Exception occurs the normal flow of the program is disturbed and the
program/Application terminates abnormally, which is not recommended,
therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the
JVM has run out of memory.
Exception Handling
Categories of Exception
Some of exceptions are caused by user error, others by
programmer error, and others by physical resources that have
failed in some manner.
Based on these, there are three categories of Exceptions.
1) Checked exceptions
A checked exception is an exception that is checked (notified) by
the compiler at compilation-time
also called as compile time exceptions.
These exceptions cannot simply be ignored, the programmer
should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read
data from a file, if the file specified in its constructor doesn't exist,
then a FileNotFoundException occurs, and the compiler prompts
the programmer to handle the exception.
Exception Handling
Categories of Exception
Example program
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo
{
public static void main(String args[])
{
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program, you will get the following exceptions.
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader fr = new FileReader(file); ^
1 error
Exception Handling
Categories of Exception
2) Un-checked exceptions
An unchecked exception is an exception that occurs at the time of execution.
These are also called as Runtime Exceptions.
These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call
the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception
occurs.
Example Program If you compile and execute the above program, you will
public class Unchecked_Demo get the following exception.
Output
{ Exception in thread "main"
public static void main(String args[]) java.lang.ArrayIndexOutOfBoundsException: 5
{ at
Exceptions.Unchecked_Demo.main(Unchecked_Demo.ja
int num[] = {1, 2, 3, 4}; va:8)
System.out.println(num[5]);
}
}
Exception Handling
Categories of Exception
3) Errors
These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer.
Errors are typically ignored in your code because you can rarely
do anything about an error.
For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
error v/s exception
Errors indicate that something severe enough has gone wrong, the
application should crash rather than try to handle the error.
Exceptions are events that occurs in the code. A programmer can
handle such conditions and take necessary corrective actions.
Exception Handling
Five keywords which are used in handling exceptions in Java.
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception. System
generated exceptions are automatically thrown by the Java run-time
system To manually throw an exception, use the keyword throw
throws The "throws" keyword is used to declare exceptions. It doesn't
throw an exception. It specifies that there may occur an exception in
the method. It is always used with method signature. Any exception
that is thrown out of a method must be specified as such by a throws
clause
Exception-Handling
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
}
8
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class. The
exception class is a subclass of the Throwable class. Other than the
exception class there is another subclass called Error which is derived from
the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these
are not handled by the Java programs. Errors are generated to indicate
errors generated by the runtime environment. Example: JVM is out of
memory. Normally, programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and
RuntimeException Class.
9
Exceptions Methods
Following is the list of important methods available in the Throwable class.
Sr.No. Method & Description
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString()
Returns the name of the class concatenated with the result of getMessage().
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output
stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the
method at the bottom of the call stack.
11
RuntimeException Exceptions
12
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
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);//NumberFormatException
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; //ArrayIndexOutOfBoundsException
Some important points
catch clause cannot exist without a try statement.
The try block cannot be present without either catch clause or finally
clause.
Any code cannot be present in between the try, catch, finally blocks.
The finally block follows a try block or a catch block. A finally block of code
always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that
you want to execute, no matter what happens in the protected code.
21
Example (Cont.)
• 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.
22
Exception Handling
// Java program to demonstrate exception is thrown
// how the runTime system searches th call stack
// to find appropriate exception handler.
class ExceptionThrown
{
// It throws the Exception(ArithmeticException).
// Appropriate Exception handler is not
// The runTime System searches the appropriate
//found within this method.
//Exception handler in this method also
static int divideByZero(int a, int b) //but couldn't have found. So looking
{ //forward on the call stack.
// this statement will cause static int computeDivision(int a, int b)
//ArithmeticException(/ by zero) {
int i = a/b; int res =0;
try
return i;
{
} res = divideByZero(a,b);
}
// doesn't matches with ArithmeticException
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException is occured");
}
return res;
}
Exception Handling
// In this method found appropriate Exception handler.
// i.e. matching catch block.
public static void main(String args[])
{
int a = 1;
int b = 0;
try
{
int i = computeDivision(a,b);
}
// matching ArithmeticException
catch(ArithmeticException ex)
{
// getMessage will print description of exception(here / by zero)
System.out.println(ex.getMessage());
}
}
} // end of class body
throw
It is possible for your program to 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
25
Example
Output:
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo 26