Java Exception Handling

Java Exception Handling

Exceptions in Java:

Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can ever escape a java error exception.

•    Unexpected events (End of File)

•    Erroneous events (Subscript out of bounds)

An exception can occur for many different reasons, including the following:

•    A user has entered 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.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.

When an exception occurs, the method currently executing creates an exception object and passes it to the runtime system, which looks for a special block of code, called an exception handler, that deals with the exception.

•    A method “throws” an exception.

•    An exception handler “catches” an exception.


•    Code that handles errors and unusual events can be separated from the normal code.

•    Errors automatically propagate up the calling chain until they are handled.

•    Errors and special conditions can be classified and grouped according to common properties.

Types of Exceptions:

The built-in exceptions in Java are categorized on the basis of whether the exception is handled by the Java compiler or not. Java consists of the following categories of built-in exceptions:
- Checked Exceptions
- Unchecked Exceptions

Checked Exceptions:

Checked exceptions are the objects of the Exception class or any of its subclasses excluding the Runtime Exception class. Checked exceptions are the invalid conditions that occur in a Java program due to invalid user input, network connectivity problem, or database problems. For example, IOException is a checked exception. The IOException exception is thrown whenever an input/output operation is abnormally terminated.
Java uses the try-catch block to handle the checked exceptions. The statements within a program that throw an exception are placed in the try block. You associate an exception-handler with the try block by providing one or more catch handlers immediately after the try block
ClassNotFoundException: Occurs when the Java run-time system is unable to find the class referred.
IllegalAccessException: Occurs when you want to refer a class that is not accessible.
InstantiationException: Occurs when you try to create an object of an abstract class or interface.
NoSuchMethodException: Occurs when you call a method that does not exist.

Unchecked Exceptions:

Unchecked exceptions are the run-time errors that occur because of programming errors, such as invalid arguments passed to a public method. The Java compiler does not check the unchecked exceptions during program compilation. For example, if you divide a number by zero, an unchecked or run-time exception is raised.

ArithmeticException: Occurs when you make an arithmetic error, such as dividing a number by zero.

ArrayIndexOutOfBoundsException: Occurs when an attempt is made to access an array element beyond the index of the array

ArrayStoreException: Occurs when you assign an element to an array that is not compatible with the data type of that array.

ClassCastException: Occurs when you assign a reference variable of a class to an incompatible reference variable of another class

IllegalArgumentException: Occurs when you pass an argument of incompatible data type to a method.

NegativeArraySizeException: Occurs when you create an array with negative size

NullPointerException: Occurs when an application tries to use an object without allocating memory to it or calls a method of a null object.

NumberFormatException: Occurs when you want to convert a string in an incorrect format to a numeric format.


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.

Exception Hierarchy:

Throwable is the base class of all exceptions in java. Throwable has two direct sub classes namely Exception and Error. These two classes create clean separation of exception types. Exception and its entire sub classes are that can be handled within the program. Error and all its sub classes are expected to be handled by the program. Error and its sub type are used by Java’s run time system to indicate problems related to run time environment like out of memory or stack overflow. For example, out of memory problem (OutOfMemoryError) cannot be fixed using program code and is not expected to be handled by the program.
With every release of java there are numerous new exceptions added to the package and we have a lot of them now. Packaging wise, every Java package has its set of exceptions organized within it. For example,* contains all IO related exceptions in* itself.
RuntimeException is a sub class of Exception class. RuntimeException and all it sub classes are need not be declared in throws clause of a method. These are understood to be regular exceptions that can occur in any context and java says that we need not declare them in throws of a method. All exceptions other than RuntimeException and its subclasses must be declared in throws clause of a method.  RuntimeException and all its sub classes are called un-checked exceptions, since they need not be declared using throws in method signature and all other java exceptions are checked exceptions.
When Exception object raised it must be handle otherwise program will terminate. Java use five key words called exception handling

•    try

•    catch

•    throw

•    throws

•    finally

The general form of exception handling block is
//block monitors error
catch (exceptiontype e)
//exception handler
// block will must execute before try ends
Try block contains code where exception may generate. Exception rose caught by catch block. The codes that must execute before a method returns or program terminated must be written in finally block. Exceptiontype shows type of exception raised.

 * Saved as
 * Show use of try and catch block

package exceptionhandling;
class Excp{
    int dividend, divisor;
    Excp (int n1, int n2)
        dividend =n2;
    public int div()
        int i=0;
        try {
        } catch (ArithmeticException e)
        System.out.println ("Divide by zero");
        return i;
public class excpexmp1 {
public static void main (String[] str)
     Excp obj=new Excp (10, 20);
     Excp ob1= new Excp (0, 10);
     System.out.println (obj.div ());
     System.out.println (ob1.div ());
Divide by zero


Exceptions can be thrown by either java run time environment or by the code itself. JRE throws exception when java’s rules are violated. An example is, when the code accesses an array location which is not available then ArrayIndexOutOfBoundsException is thrown. All the java exception classes are not having any attributes and standard methods. It is a common design. Class name describes what exception it is and the hierarchy forms an organization chart kind of structure using which java exceptions are used.
Programmers can throw an exception to indicate a problem condition. Either java’s predefined exceptions can be used or custom exceptions can be created by extending the already available exceptions. Programmer can throw a custom exception or a predefined Java exception. Mostly custom exceptions are created based on business conditions. Programmer can use the Java keyword ‘throw’to generates an exception. It is done by instantiating the exception class of choice and then thrown.

try – catch:

A thrown exception should be handled. If the program does not handle an exception, then it will be handled by the java run time environment. A block of code where an exception is expected should be surrounded by try – catch block. try indicates the start of the exception handling block and catch the end of the block. Following catch a block of code can be written which is the exception handling code block. This is the part the handles the exception. A catch will have an exception identified and it will catch only that type of exception. Type means the same exception and all its sub classes. There can be multiple catch blocks for a try block.


When a Java method is going to throw an exception, to indicate that as part of the method signature ‘throws’ keyword should be used followed by the exception. It means that the caller of this method should handle the exception given in the throws clause. There can be multiple exceptions declared to be thrown by a method. If the caller of that method does not handles the exception, then it propagates to one level higher in the method call stack to the previous caller and similarly till it reaches base of the method call stack which will be the java’s run time system.


After catch block there can be one more block of code declared as ‘finally‘. Irrespective of whether an exception is thrown or not, the finally block of code will always be executed. Important piece of code that must be executed, even if a program fails belong to this finally block. Example would be closing a database connection, a file handle, etc.

Exception Propagation:

If it is not appropriate to handle the exception where it occurs, it can be handled at a higher level.
Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the outermost level.
A try block that contains a call to a method in which an exception is thrown can be used to catch that exception.

static void method1 throws IOException {
throw new IOException ("Error in method1");
static void method2 throws IOException {
// do stuff, but no catch, just specify
method1 ();
static void method3 throws IOException {
// do stuff, but no catch, just specify
method2 ();
public static void main (String args []) {
// catch if just specify error to console
try {
method3 ();
} catch (IOException e) {
// handle the exception from method1


I am not able to copy the code mentioned above.

Post a Comment