Module 4
Module 4
Unit-4
Introduction
An exception is an event that occurs during the execution of a program that disrupts
the normal flow of instruction.
o Or
An abnormal condition that disrupts Normal program flow.
There are many cases where abnormal conditions happen during program execution,
such as
o Trying to access an out - of –bounds array elements.
o The file you try to open may not exist.
o The file we want to load may be missing or in the wrong format.
o The other end of your network connection may be non –existence.
If these cases are not prevented or at least handled properly, either the program will
be aborted abruptly, or the incorrect results or status will be produced.
When an error occurs within the java method, the method creates an exception
object and hands it off to the runtime system.
The exception object contains information about the exception including its type and
the state of the program when the error occurred. The runtime system is then
responsible for finding some code to handle the error.
In java creating an exception object and handling it to the runtime system is
called throwing an exception.
Exception is an object that is describes an exceptional (i.e. error) condition that
has occurred in a piece of code at run time.
When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error. That method may choose
to handle the exception itself, or pass it on. Either way, at some point, the exception
is caught and processed.
System generated exceptions are automatically thrown by the Java runtime system
Acharya MCA
Acharya MCA
As you can see from the image above, the Throwable class is the root class in the hierarchy.
Note that the hierarchy splits into two branches: Error and Exception.
There are some important methods available in the Throwable class which are as follows:
public String getMessage() – Provides information about the exception that has occurred through a
message, which is initialized in the Throwable constructor.
public Throwable getCause() – Provides root cause of the exception as represented by a Throwable
object.
public void printStackTrace() – Used to display the output of toString() along with the stack trace
to System.err (error output stream).
Acharya MCA
Acharya MCA
public StackTraceElement [] getStackTrace() – Returns an array with each element present on the
stack trace. The index 0 element will symbolize the top of the call stack, and the last element of array
will identify the bottom of the call stack.
2. IOException
An IOException is also known as a checked exception. They are checked by the compiler at the
compile-time and the programmer is prompted to handle these exceptions.
Some of the examples of checked exceptions are:
Trying to open a file that doesn’t exist results in FileNotFoundException
Trying to read past the end of a file
Acharya MCA
Acharya MCA
abruptly, which can lead to data loss & other issues. With proper exception handling, the program
can continue to execute and provide a more stable user experience.
2. Enhances the Robustness of the Program
Exception handling allows for the program to anticipate and recover from errors, thus making the
program more robust and resistant to unexpected conditions. By catching and handling exceptions,
the program can continue to execute and provide a more stable user experience.
3. Improves the Readability & Maintainability of the Code
Proper exception handling also improves the readability & maintainability of the code. By catching
and handling exceptions, the program can provide clear error messages that accurately describe the
error and provide information on how to resolve the issue. This makes it easier for developers to
understand and modify the code in the future. Additionally, by providing detailed error messages,
proper exception handling allows for more accurate error reporting, which is essential for debugging
and troubleshooting purposes.
4. Allows for more Accurate Error Reporting
Exception handling allows the program to catch & report errors in a more accurate & detailed
manner, providing valuable information to developers for debugging and troubleshooting purposes.
5. Facilitates Debugging and Troubleshooting
Exception handling allows the program to catch & report errors in a more accurate and detailed
manner, which facilitates debugging and troubleshooting. By providing detailed error messages and
stack traces, exception handling allows developers to quickly identify and resolve issues, reducing
the amount of time and resources required for debugging.
6. Improves the Security of the Program
Exception handling can also improve the security of a program by preventing sensitive information
from being exposed in the event of an error. By catching and handling exceptions, the program can
prevent sensitive information, such as passwords and personal data, from being displayed to the user
or logged-in error messages.
7. Provides a Better user Experience
Proper exception handling allows the program to anticipate and recover from errors, providing a
more stable user experience. It is particularly important for user-facing applications, as it ensures that
the program continues to function even in the event of an error, reducing the likelihood of user
frustration and abandonment.
8. Enables the use of error-recovery Mechanisms
Exception handling enables the use of error-recovery mechanisms, such as retries or fallbacks, which
can improve the reliability and availability of the program. For example, if a program encounters a
network error, it can retry the operation or fall back to a different network connection, ensuring that
the program continues to function even in the event of an error.
9. Improves the Scalability and Performance of the Program
Proper exception handling can also improve the scalability and performance of a program by
reducing the amount of unnecessary processing and resource consumption. By catching and handling
exceptions, the program can avoid performing unnecessary operations and releasing resources that
are no longer needed, reducing the overall load on the system and improving performance.
Acharya MCA
Acharya MCA
Try Block
No
arise or
Catch Block
No Exceptional Handler
appropriate
Catch
block
Finally Block
Optional part
Acharya MCA
Acharya MCA
For Example:
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.
Any exception that is not caught by your program will ultimately be processed by
the default handler. The default handler displays a string describing the exception,
prints a stack trace from the point at which the exception occurred, and terminates
the program. Here is the output generated when this example is executed.
java.lang.ArithmeticException
: / by zero at
Exc0.main(Exc0.java:4)
We know that exceptions abnormally terminate the execution of a program. This is why it
is important to handle exceptions. Here's a list of different approaches to handle exceptions
in Java.
try...catch block
finally block
throw and throws keyword
Acharya MCA
Acharya MCA
// code
}
Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by a catch block.
Catch block
The catch block is used to process the exception raised. A try block can be one or more
catch blocks can handle a try block. Catch handles are placed immediately after the try
block. When an exception occurs, it is caught by the catch block. The catch block
cannot be used without the try block.
Acharya MCA
Acharya MCA
int c = a / b;
System.out.println("a / b = " + c);
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception has occurred in the program");
System.out.println("The message of the exception is: " + e.getMessage());
}
catch (Exception e) {
System.out.println("Some general Exeption has occurred in the program");
System.out.println("The message of the exception is: " + e.getMessage());
}
}
}
Acharya MCA
Acharya MCA
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
Output:
ArithmeticException => / by zero
This is the finally block
Catch block
The catch block is used to process the exception raised. A try block can be
one or more catch blocks can handle a try block.
Catch handles are placed immediately after the try block.
Catch(exceptiontype e)
{
//Error handle routine is placed here for handling exception
}
Program 1
Class trycatch
{
Public static void main(String args[])
{
Int[] no={1,2,3};
Try
{
System.out.println(no[3]);
Acharya MCA
Acharya MCA
}
Catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Out of bonds”);
}
System.out.println(―Quit‖);
}
}
Output
Out of the Range Quit
Program 2:
class ArithExce
{
public static void main(String args[])
{
int a=10,b=0;
try
{
a=a/b;
System.out.println(―Won’t Print‖);
}
Catch(ArithmeticException e)
{
System.out.println(―Division by Zero error‖); System.out.println(―Change the b value‖);
}
System.out.println(―Quit‖);
}
}
Output
Division By zero error
change the B value
Quit
Acharya MCA
Acharya MCA
Note:
A try and its catch statement form a nit. We cannot use try block alone.
The compiler does not allow any statement between try block and its
associated catch block.
Acharya MCA
Acharya MCA
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.
The following example traps two different exception types:
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
system.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no
command line parameters, since a will equal zero. It will survive the division if
you provide a command-line argument, setting a to something larger than
zero. But it will cause an
Acharya MCA
Acharya MCA
Throw Keyword
So far, we have only been catching exceptions that are thrown by the Java
Run –Time systems. How ever, it is possible for our program to throw an
exception explicitly, using the throw statement.
Throw throwableInstance
Here, ThrowableInstance must be an object of type Throwable or a subclass
of Throwable. Simple types, such as int or char, as well as non-Throwable
classes, such as String and Object, cannot be used as exceptions
There are two ways you can obtain a Throwable object:
– using a parameter into a catch clause
– creating one with the new operator.
The flow of execution stops immediately after the throw statement; any
subsequent statements are not executed. The nearest enclosing try block is
inspected to see if it has a catch statement that matches the type of the
exception. If it does find a match, control is transferred to that statement. If
not, then the next enclosing try statement is inspected, and so on. If no
matching catch is found, then the default exception handler halts the
program and prints the stack trace
// Demonstrate throw.
class ThrowDemo {
static void demoproc()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
Acharya MCA
Acharya MCA
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
}
catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
This program gets two chances to deal with the same error. First, main( )
sets up an exception context and then calls demoproc( ). The demoproc( )
method then sets up another exception-handling context and immediately
throws a new instance of NullPointerException, which is caught on the next
line. The exception is then rethrown. Here is the resulting output:
The program also illustrates how to create one of J close attention to this line:
Throws Keyword
You do this by including a throws clause in the method’s throws clause lists
declare the types of exceptions that a method might throw. This is necessary
Acharya MCA
Acharya MCA
for all exceptions, except those of type Error or RuntimeException, or any
of their subclasses. All other exceptions that a method can throw must be
declared in the throws clause. If they are not, a compile-time error will
result. This is the general form of a method declaration that includes a
throws clause:
Acharya MCA
Acharya MCA
Finally block
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
system.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {
system.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
}
finally {
System.out.println("procB's finally");
Acharya MCA
Acharya MCA
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
}
finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
}
catch (Exception e)
{
System.out.println("Exception caught");
}
procB();
procC();
}
}
In this example, procA( ) prematurely breaks out of the try by throwing an
exception. The finally clause is executed on the way out. procB( )’stry
statement is exited via a return statement. The finally clause is executed
before procB( ) returns. In procC( ), the try statement executes normally,
without error. However, the finally block is still executed. If a finally block
is associated with a try, the finally block will be executed upon conclusion
of the try.
Acharya MCA
Acharya MCA
There are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:
Acharya MCA
Acharya MCA
void disp(){
// reassigining the name variable
// that throws compile time error
name = "Ganesh";
}
Acharya MCA
Acharya MCA
Acharya MCA
Acharya MCA
Examples:
1. ArithmeticException:
public class ArithmeticExceptionExample {
2. ArrayIndexOutOfBoundsException
public class ArrayIndexOutOfBounds {
public static void main(String[] args) {
int[] nums = new int[] {
1,
2,
3
};
try {
int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
int numFromGreaterIndex = nums[4]; // Trying to access at greater index
int numFromLengthIndex = nums[3]; // Trying to access at index equal to size
of the array
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.println("ArrayIndexOutOfBoundsException caught");
e.printStackTrace();
}
}
}
Output:
ArrayIndexOutOfBoundsException caught
java.lang.ArrayIndexOutOfBoundsException: -1
at com.javaguides.corejava.ArrayIndexOutOfBounds.main(ArrayIndexOutOfBounds.java:10)
Acharya MCA
Acharya MCA
3. ClassCastException
The ClassCastException is a runtime exception that Java throws when code
attempts to cast an object to a subclass it doesn't belong to. In simpler terms, it arises
when we mistakenly try to treat one type of object as another incompatible type.
Here is a very simple example, an Integer object cannot be cast to a String object:
Example:
public class ClassCastExceptionExample {
public static void main(String[] args) {
Object obj = new Integer(100);
System.out.println((String) obj);
}
}
Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be
cast to java.lang.String
at ClassCastExceptionExample.main(ClassCastExceptionExample.java:4)
1.ClassNotFoundException:
The ClassNotFoundException is a checked exception that signals the Java Runtime
Environment (JRE) cannot find the specified class in its classpath during runtime. It's
important to note that this is different from the NoClassDefFoundError, which occurs
when the class was available during compile-time but not at runtime.
2. FileNotFoundException:
FileNotFoundException is a checked exception in Java, which means you're required to
handle it, either by catching it or declaring it in the method signature using the throws
keyword. It's thrown primarily by the Java I/O system when attempting to access a file
that doesn't exist or isn't accessible for some reason.
In the below example, an invalid path location passed to the File constructor leads
to this exception.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
Acharya MCA
Acharya MCA
System.err.println("FileNotFoundException caught!");
e.printStackTrace();
}
}
}
Output:
FileNotFoundException caught!
java.io.FileNotFoundException: \invalid\file\location (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at com.javaguides.corejava.FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:15)
3. InterruptedException:
When a thread is blocked (waiting, sleeping, or occupied with some long-running
operations) and another thread interrupts it by invoking its interrupt() method, the
blocked thread throws an InterruptedException. This mechanism allows threads to be
stopped, queried, and controlled.
In the below example, note that the thread interrupted in the main() method throws
an InterruptedException exception that is handled in the run() method.
Acharya MCA
Acharya MCA
class VoterList{
int age;
VoterList(int age){
this.age = age;
}
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for vote.");
}
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {
Example 2:
// This program creates a custom exception type.
Acharya MCA