Java Programming Unit-III Part-I
Java Programming Unit-III Part-I
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)
UNIT-III PART-I
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 in java programming is an abnormal situation that is raised during the program
execution. In simple words, an exception is a problem that arises at the time of program
execution.
When an exception occurs, it disrupts the program execution flow. When an exception
occurs, the program execution gets terminated, and the system generates an error. We use
the exception handling mechanism to avoid abnormal termination of program execution.
Java programming language has a very powerful and efficient exception handling
mechanism with a large number of built-in classes to handle most of the exceptions
automatically.
Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 2
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)
Java programming language has the following class hierarchy to support the exception
handling mechanism.
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the
compilation process to confirm whether the exception is handled by the programmer or not.
If it is not handled, the compiler displays a compilation error using built-in classes. The
checked exception is also known as a compile-time exception.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
IOException
FileNotFoundException
ClassNotFoundException
SQLException
DataAccessException
InstantiationException
UnknownHostException
Note:
In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.
Example:
import java.io.*;
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation. The
unchecked exception is also known as a runtime exception.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper
use of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
Example:
public class UncheckedException {
System.out.println(list[6]); //ArrayIndexOutOfBoundsException
Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 5
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)
String msg=null;
System.out.println(msg.length()); //NullPointerException
String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at UncheckedException.main(UncheckedException.java:7)
Termination Model
Resumptive Model
Termination Model
In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the
type of exception encountered.
Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the
exception handler is expected to do something to stable the situation, and then the faulting
method is retried. In resumptive model we hope to continue the execution after the
exception is handled.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allows us
to handle the exception use the keywords like try, catch, finally, throw and throws.
When an uncaught exception occurs, the JVM calls a special private method known
dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions.
Prepared by N.Venkateswaran, Associate Professor, CSE Dept Page 6
JYOTHISHMATHI INSTITUTE OF TECHNOLOGY AND SCIENCE
KARMNAGAR
(Approved by AICTE, New Delhi and- Affiliated
505481 to JNTU, Hyderabad)
In the above example, we are not used try and catch blocks, but when the value of b is zero
the division by zero exception occurs and it caught by the default exception handler.
In java, the try and catch, both are the keywords used for exception handling.
The try block contains a set of statements where an exception can occur. It is always
followed by a catch block, which handles the exception that occurs in the associated try
block. A try block must be followed by catch blocks or finally block or both.
A catch block is where you handle the exceptions. This block must follow the try block and
a single try block can have several catch blocks associated with it. You can catch different
exceptions in different catch blocks. When an exception occurs in a try block, the
corresponding catch block that handles that particular exception executes.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks.
We cannot use try without atleast one catch, and catch alone can be used (catch without try
is not allowed).
The following is the syntax of try and catch blocks.
Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}
Example:
import java.util.Scanner;
In the above example code, when an exception occurs in the try block the execution control
transferred to the catch block and the catch block handles it.
When a try block has more than one catch block, each catch block must contain a different
exception type to be handled.
The multiple catch clauses are defined when the try block contains the code that may lead to
different type of exceptions.
The try block generates only one exception at a time, and at a time only one catch block is
executed.
When there are multiple catch blocks, the order of catch blocks must be from the most
specific exception handler to most general.
The catch block with Exception class handler must be defined at the last.
Example:
public class TryMCatchExample {
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
catch(Exception e) {
When there are nested try blocks, each try block must have one or more separate catch
blocks.
Example:
public class TryCatchMNExample {
public static void main(String[] args) {
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try {
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor cannot be ZERO.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}
Output:
Problem info: ArrayIndexOutOfBoundsException has occurred.
The throw keyword must be used inside the try block. When JVM encounters the throw
keyword, it stops the execution of try block and jump to the corresponding catch block.
Using throw keyword only object of Throwable class or its sub classes can be
thrown.
Using throw keyword only one exception can be thrown.
The throw keyword must followed by a throwable instance.
The following is the general syntax for using throw keyword in a try block.
Syntax
throw instance;
Here the instance must be throwable instance and it can be created dynamically using new operator.
Example:
import java.util.Scanner;
When a method throws an exception, we must put the calling statement of method in try-catch block.
Example:
import java.util.Scanner;
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}
throw vs throws
throw throws
1. Used to explicitly throw an exception 1. Used to declare an exception
2. Checked exceptions cannot be propagated using
2. Checked exceptions can be propagated
throw only
3. Followed by an instance 3. Followed by a class
4. Used within a method 4. Used with a method signature
5. Cannot throw multiple exceptions 5. Can declare multiple exceptions
A finally block contains all the crucial statements that must be executed whether an
exception occurs or not. The statements present in this block will always execute, regardless
an exception occurs in the try block or not such as closing a connection, stream etc.
The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
The Java programming language allows us to create our own exception classes which are
basically subclasses built-in class Exception.
To create our own exception class simply creates a class as a subclass of built-in Exception
class.
We may create constructor in the user-defined exception class and pass a string to Exception
class constructor using super(). We can use getMessage() method to access the string.
The following Java code that illustrates the creation of user-defined exception.
Example:
import java.util.Scanner;
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[]) {