javascript
Brief description  about Online courses   join in Online courses
OR

Exceptions Handling

Alpana  Gupta
Alpana Gupta
Software engineer
"An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions."

Consider the below Java program:

class ExceptionIntro    {
    public static void main(String args[ ])
        {
            int a,b;
            a=10;
            b=Twenty;
            System.out.println("Value of variable a is" +a);
            System.out.println("Value of variable b is" +b);
        }
}

When we compile the above program we will get the below exception:

ExceptionIntro.java:6: cannot find symbol
symbol  : variable Twenty
location: class ExceptionIntro
            b=Twenty;
              ^
1 error

In the above program we have declared 'b' as int and we have initialized 'b' to TWENTY which is not a valid number. Here, our compiler will be expecting 'b' to associated with a valid number but it will encounter a wrong type and will throw an error/exception.

When we write code we should take care of situations like the one we saw above. Here, we should take care of exceptions like this in our program and many more which we will be discussing in future.

In this section we will discuss about how we can handle exceptions in our programs.

If you are done with the above sections, please get the assignment using below option.
 Get assignment
Next chapter >>
Exceptions
Exception Classification


There are 3 types of exception we will encounter in our Java program:
1. Checked Exception
2. Errors
3. Runtime Exception

CHECKED EXCEPTION
These are the exceptions or we can also say exceptional conditions that our program should anticipate and should recover from it when it encounters it. A simple example is that when we write a program to read from a file(file will be the input of our program) then the program expects the file to be available in the location we specify. If the file is not available then the program encounters an exceptional condition which shoul dbe handled properly.

We will be discussing this type of exception in a more detailed way throughout this section. Checked Exception are handled using Catch blocks which we will discuss shortly.

ERRORS
These are the type of exception which cannot be anticipated by our program. For example, in our previous discussion if the file exists and the program cannot access the file due to a hardware problem. In this case our program might throw a java.io.IOError which again can be handled by our program.

RUNTIME EXCEPTION
These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API.
Consider the previous example, our program successfully reads the file as input but in the file we have specified a line which passes null to a constructor.
OOPS! this will be a problem, in this case our program will throw NullPointerException.

It is best advised that the code which causes this type of exception should be fixed and executed again.

Please note that we already have a set of exception handlers which is readily available, for example:
1. For Errors - Error and subclasses within it.
2. For Runtime Exceptions - RuntimeException and subclasses within it.

Errors and runtime exceptions are collectively known as unchecked exceptions.

If you are done with the above sections, please get the assignment using below option.
 Get assignment
<< Previous chapter
Next chapter >>
Exceptions
Encountering An Exception


We have seen that there will be exceptions in our program and we cannot avoid that. However, What do we do if our program encounters an Exception? It obviously can't abruptly stop and exit. Just imagine! You have written a program to analyze the trends of the stock market and suddenly the program encounters an exception and stops working. This will be annoying isn't it? To overcome this, we have a feature in Java which takes care of exception and tries to keep the program running even after encountering it. In this Chapter we will have a look at how we will do it.

Have a look at the below program:

public class ExceptionExample1    {
   
    public static void main(String args[ ])    {
        int num1 = 100;
        int num2 = 4;
        int Answer = num1/num2;
        System.out.println("Answer is: " +Answer);
    }
}

Output:
Answer is: 25

In the above program we have divided num1 (numerator) with num2 (denominator) and printed the answer on the screen. This program works perfectly fine.

Now have a look at the below program:

public class ExceptionExample1    {
   
    public static void main(String args[ ])    {
        int num1, num2, Answer;
        num1 = 100;
        num2 = 0;
        Answer = num1/num2;
        System.out.println("Answer is: " +Answer);
    }
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ExceptionExample1.main(ExceptionExample1.java:6)

In the above program we have changed the value of num2 (denominator) to 0 and this will very obviously cause an error because we cannot divide a number with zero.

In this case our program just throws the above java.lang.ArithmeticException and exits. As I mentioned earlier just imagine if you have written a program to analyze the trends of Stock Market and someone just gives an input to divide a number by zero and BAMMM! Your program exits abruptly... Thats not fair! We will see how we can overcome this kind of situation in next few chapters of this section.

If you are done with the above sections, please get the assignment using below option.
 Get assignment
<< Previous chapter
Next chapter >>
Exceptions
Exception Handling


In our previous chapter we saw that how our program can become useless by an exception. In Java, we might encounter several exceptions and few common ones are:

1) Arithmetic Exception - very common exception which occurs when there is any error in the arithemetic operation
2) NullPointer Exception - happens if u specify a wrong or unavailable destination
3) ArrayIndexOutOfBounds Exception - happens if u point the unavailable index of the array
4) NegativeArraySizeException - happens when u specify negative size for array
5) NumberFormat Exception - happens in the case of wrong number format

To handle exceptions we have a feature which allow us to take care of exceptions while we meet them and they are:
1. TRY BLOCK
2. CATCH BLOCK

TRY BLOCK
This is the block which encloses the part of our program which might throw an exception. To use this we must first identify the part of our program which we think might throw an exception.

In general, a TRY block will look like this:

try    {
    //Code we think which might throw an exception
}

CATCH BLOCK
Once we know which part of our program throws the exception there should be something which should be there to catch it. This 'CATCH' Block does exactly that. This block contains the instruction to program which tell what it should do if an exception is thrown.

In general, a CATCH block will look like this:

catch ( exception e)    {
    //Code that handes the exception
}

Here, (exception e) is nothing but the type of exception that the code will catch.

We will have a look at these blocks with respect to our example in the next chapter.

If you are done with the above sections, please get the assignment using below option.
 Get assignment
<< Previous chapter
Next chapter >>
Exceptions
The Try Block


Lets recall our example we discussed in Chapter 3 - Encountering An Exception

public class ExceptionExample1    {
   
    public static void main(String args[ ])    {
        int num1, num2, Answer;
        num1 = 100;
        num2 = 0;
        Answer = num1/num2;
        System.out.println("Answer is: " +Answer);
    }
}

We know that the above program throws an Arithmetic Exception and we also know that the below part of program throws the exception:

        int num1, num2, Answer;
        num1 = 100;
        num2 = 0;
        Answer = num1/num2;
        System.out.println("Answer is: " +Answer);

Now we will put the risky part of the program within our try block highlighted in Green:

public class ExceptionExample1    {
   
    public static void main(String args[ ])    {
        try    {
            int num1, num2, Answer;
            num1 = 100;
            num2 = 0;
            Answer = num1/num2;
            System.out.println("Answer is: " +Answer);
        }   
    }
}

We will compile this program and see what happens!

Output:
ExceptionExample1.java:4: 'try' without 'catch' or 'finally'
        try    {
        ^
1 error

We get an error saying that there is no catch block. We will have a look at the Catch Block in our next chapter and there is also something called as "Finally' which we will look at a little later in this section.



If you are done with the above sections, please get the assignment using below option.
 Get assignment
<< Previous chapter
Next chapter >>
Exceptions
The Catch Block


We will have a look at the example we had in the previous chapter:

public class ExceptionExample1    {
   
    public static void main(String args[ ])    {
        try    {
            int num1, num2, Answer;
            num1 = 100;
            num2 = 0;
            Answer = num1/num2;
            System.out.println("Answer is: " +Answer);
        }   
    }
}

We know that this program won't get compiled as there is no catch block. We will implement the catch block in the below program highlighted in Green:

public class ExceptionExample1    {
   
    public static void main(String args[ ])    {
       
        try    {
            int num1, num2, Answer;
            num1 = 100;
            num2 = 0;
            Answer = num1/num2;
            System.out.println("Answer is: " +Answer);
        }
       
        catch(Exception e)    {
            System.out.println("CAUTION: Don't Do this!!");
        }
    }
}

Output:
CAUTION: Don't Do this!!

In the above catch block we have used (Exception e). Here Exception is nothing but the class that contains all types of exceptions in Java. This Exception class is part of java.lang package and contains all exceptions which are actually subclasses of Exception class.

If you observe you will see that there is a lot of difference between the output we got earlier and the one we got now.

Lets have a look at it again:

Output before introducing try and catch blocks:
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ExceptionExample1.main(ExceptionExample1.java:6)

Output after introducing try block but not catch block:
ExceptionExample1.java:4: 'try' without 'catch' or 'finally'
        try    {
        ^
1 error

Output after introducing try and catch blocks:
CAUTION: Don't Do this!!

By analyzing the above set of output, we see that:
- Without try and catch blocks an exception is thrown by the application itself
- Try block alone is not sufficient and should always be followed by catch block
- When an exception is encountered then the code within the catch block is executed
- Try block is executed at least once in our program

If you are done with the above sections, please get the assignment using below option.
 Get assignment
<< Previous chapter
Next chapter >>
Exceptions
The Finally Block


This is an optional block in our exception handling part of our program. We use finally keyword to catch any unexpected exception that is thrown by the try block. The finally block will be always executed in our program irrespective of whether the try block throws an exception or not.

Lets have a look at our finally block using our example:

public class ExceptionExample1    {
   
    public static void main(String args[ ])    {
       
        try    {
            int num1, num2, Answer;
            num1 = 100;
            num2 = 0;
            Answer = num1/num2;
            System.out.println("Answer is: " +Answer);
        }
       
        catch(Exception e)    {
            System.out.println("CAUTION: Don't Do this!!");
        }
       
        finally    {
            System.out.println("This is printed from finally block");
        }   
    }
}

Output:
CAUTION: Don't Do this!!
This is printed from finally block

In the above program we have introduced a finally block that prints the line "This is printed from finally block" and this will be always printed when the program executed.

Here, the try block throws an exception which is handled by the catch block (prints the line "CAUTION: Don't Do this!!") after which the finally block is executed.

Now, we will fix the above exception by changing num2 to non-zero value and see what happens.

public class ExceptionExample1    {
   
    public static void main(String args[ ])    {
       
        try    {
            int num1, num2, Answer;
            num1 = 100;
            num2 = 2;
            Answer = num1/num2;
            System.out.println("Answer is: " +Answer);
        }
       
        catch(Exception e)    {
            System.out.println("CAUTION: Don't Do this!!");
        }
       
        finally    {
            System.out.println("This is printed from finally block");
        }   
    }
}

Output:
Answer is: 50
This is printed from finally block

As you can see above we have changed the value of num2 from 0 to 2 and the program executes normally but still the finally block is executed.

Write your comment now