Course Content‎ > ‎Session 10‎ > ‎

Intro to Exception Handling

An exception is an event, which is not expected to occur in the normal operation
of a program. When an exceptional condition causes an exception to be thrown,
that exception is an object derived, either directly, or indirectly from the
class Throwable. The Throwable class has two subclasses:

    1. Error: An Error indicates that a non-recoverable error has occurred, that
       should not be caught. Errors usually cause the Java interpreter to display
       a message and exit.
    
    2. Exception: An Exception indicates an abnormal condition, that must be
       properly handled to prevent program termination. All exceptions other than
       those in the RuntimeException class must be either caught or declared.
       Exceptions can occur for many reasons, for example, dividing a number by
       zero; trying to access an array element which doesn't exist.

All errors and exceptions may have a message associated with them, which can be
accessed using the getMessage() method. You can use this method to display a
message, describing the error or exception.

Here is the general syntax of exception handling in Java:

    try 
    {
        //Code which might cause an exception
    } 
    catch(Exception e) 
    {
        //Exception handling code
    }

What happens when an exception occurs in Java ?

When an exception occurs in Java, an Object is created, which is of the Exception
type, this is then thrown, until it is caught. If an exception occurs in a Java
program and is left unhandled, the program will stop executing and the user will
see a runtime error. The following code generates such a runtime error by
attempting to access an array element, which doesn't exist.

    class exceptionExample
    {
        public static void main(String[] args)
        {
            int array[] = new int[9];
            int index = 10;
            array[index] = 3; //illegal, since array has 10 elements
        }
    }

Comments