Blog Image

Exception Handling  

We usually write code in an idealized environment, But sometimes, the code can experience errors while executing our instructions. To handle failures Java has one of the powerful mechanism to handle runtime errors ie Exception Handling, here we will discuss about Exceptions and Exception Handling.

Exception:

Exceptions are the means through which the JVM will gather the failure information about the execution of the program and should report the information back to the program.

The JVM will gather the following information:

  • Point of failure related to the instructions being failed.
  • State of an object.
  • The failure information that has been arrived during the execution of the particular instruction.

All this information is wrapped in an object called Exception and reported back to the program to let the program to understand the failure.

On the other hand, Error is often fatal in nature and recovery from Error is not possible which is different in case of Exception which may not be fatal in all cases.

Exception Handling:

Exceptions give the program a chance to recover out of failure that has been encountered. This is the main purpose of exception handling. When a program is running into failure rather than abnormally terminating the program if the JVM will report the failure information back to the program then the program can decide whether it has to terminate by itself or it has to continue to execute the program by having an alternate path of execution or not.

There are two types of Exceptions:

  • Exceptions which have an alternate path of execution are Checked Exceptions.
  • Exceptions which may not have an alternate path of execution are Unchecked Exceptions.

The problems which have an alternate path of execution we write in Try and Catch block.

Try Catch:

Compared to other languages Java has provided very good support for exception handling. Try, catch and finally are the three blocks in Java for exception handling mechanism. In our program, if there is a chance of exception then we should write that piece of code inside try block. If a program run into exception then for the control comes to catch block. Catch block should contain the alternate path of execution or clean up logic. Beside try and catch blocks, finally, block executes always. We should write clean up logic like closing connection etc. inside finally block.

How to know which exception is Checked/Un-Checked

Whenever we encounter any failure we should report it or we should handle it, this is where we should gather the information about the failure in an exception. Those who are designing the exception should decide whether the exception is recoverable or not based on the requirement of the application. Based on this we should design our exception.

Java provided two classes to classify checked exception and Unchecked Exception:

  • Exception Class.
  • Runtime Exception Class.

Base class of these exceptions is Throwable.

  • Any classes that Extending from Exception class is checked Exception.
  • The Classes which are extending from Runtime Exception is Un-Checked Exception.

Throws:

If a program is throwing a checked exception and we want to let it be compiled without writing alternate path of execution, then we need to tell java compiler asking it to ignore that exception and let the program being compiled by declaring as throws exception.

  • Asking compiler to ignore, Let the program be compiled.
  • Letting the callee know the details of an exception being reported.

Throws exception is for readability of code. Itís not a functional thing.

Throw:         

In some circumstances when the underlying code that you are using is not throwing exception but business requirement ask us to write a checked exception, let others decide to provide another path of execution or terminate it. Here we need to use Throw.

Example: Booking a movie Ticket, Ticket details what user fills are valid but a movie is not there in theatre at that moment, in such cases we have to let the user decide whether they want to continue with other movie or terminate the execution, thus, we have to throw an exception.

Checked Exceptions Vs Un-Checked Exceptions:

Checked exceptions are the exceptions who have an alternate path of execution but unchecked exceptions donít have. If we can handle an exception by providing some alternate path then that is called a checked exception.

Java identified some common scenarios where exceptions may arise frequently or those conditions have a high risk of falling in exceptions but those are recoverable as well using some alternate path like FileNotFoundException, SQLException etc.

People will not write that risky code in try and catch block by following the advice of Java because no one cares about advice or best practices.

That is the reason Java identified most of the scenarios where the code may run into an exception and written exception classes for every scenario.

Now wherever there was a chance where the developerís code may run into an exception, Java people wrote their classes logic inside try and catch block and inside catch block they caught specific exceptions or thrown the exception.

Now if the developer wants to use those Java classes inside his code, he has to handle that exception using try and catch or have to throw that exception to the caller because the Java class is surrounded with the try and catch block or Java methods are written to throw an exception.


FileInputStream class:

package java.io
class FileInputStream {
    public int read() throws IOException {
        // file reading logic
    }
}

Now if we want to use FileInputStream class to read the file, we need to handle the exception that is being thrown by FileInputStream class read() method.


Test class:
class Test {
    public static void main(String [] args) {
        try {
            FileInputStream fis = new FileInputStream(abc.txt);
            while(fis.hasNext()) {  
                System.out.println(fis.read());
            }
        }
    }
}

Mandatory to write this logic in try and catch block or has to throw because read() method is throwing IOException.

This way Java forced developers to write the risky code that may run into the exception but can be recovered inside try and catch block.

Types of Exceptions:

Built-In Exceptions

Arithmetic Exception: It is thrown when an exceptional condition has occurred in an arithmetic operation.

ArrayIndexOutOfBoundException: It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

ClassNotFoundException: This Exception is raised when we try to access a class whose class definition is not found

FileNotFoundException: This Exception is raised when a file is not accessible or does not open.

IOException: It is thrown when an input-output operation failed or interrupted

InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.

NoSuchFieldException: It is thrown when a class does not contain the field (or variable) specified.

NoSuchMethodException: It is thrown when accessing a method which is not found.

NullPointerException: This exception is raised when referring to the members of a null object. Null represents nothing

NumberFormatException: This exception is raised when a method could not convert a string into a numeric format.

StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an index is either negative than the size of the string.

Custom Exceptions:

Java exceptions cover almost all the exceptions but some at specific business requirements we need custom exceptions helping the developers or the end users to understand what exactly the problem is. In Java, we can define our own exceptions as per our requirements these exceptions are called User-defined Exceptions or Custom Exceptions. User-defined exceptions must extend any one of the classes in the hierarchy of exceptions.

That's all Folks!! Happy Learning.

About author

User Image
ParulG

An ardent learner of technologies based on Java, keenly interested in the Integration tier technologies like Web Services and Restful Services. Well versed in open sources like Spring, Hibernate etc. Believes in Steep Learning Curve & Perseverance.

1

-Comments

Be the first person to write a comment for this Blog
  • author image
    by:
      Renukac
      15 Jan, 2019 09:42

    Thanks for providing detailed blog, well written and very helpful.

Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.