Exception Handling in Java | Part-1

In this article, we're going to talk about Exception in Java.



What is an exception?


An unexpected, unwanted event that disturbs the normal flow of the program is called an exception. It is highly recommended to handle the exception. The main objective of exception handling is the graceful termination of the program.

Exception handling doesn't mean repairing an exception, we have to provide an alternative way to continue the rest of the program normally is the concept of exception handling.

Ex. The program requirement is read data from the remote file but at runtime remote file is not available then our program should not be terminated abnormally. We have to provide some local file to continue the program normally. This way of defining alternative is nothing but exception handling

try{
   Read file from remote place
}catch (FileNotFoundException ex)
   use local file and continue rest of the program normally
}

Runtime stack mechanism:


For every thread, JVM will create a runtime stack. Each and every method call performed by that thread will be stored in the corresponding stack. Each entry in the stack is call stack frame or activation record.

After completing every method call, the corresponding entry from the stack will be removed. After completing all method calls the stack will become empty, that empty stack will be removed by JVM just before terminating the thread.

public class Test {
    public static void main(String[] args) {
        doStuff();
    }

    private static void doStuff() {
        doMoreStuff();
    }

    private static void doMoreStuff() {
        System.out.println("Hello");
    }
}

Internal stack details are described in the below diagram:



Default exception handling in java


Inside a method, if any exception occurs, the method in which it is raised is responsible to create an exception object by including the following information:

  • Name of exception

  • Description of Exception

  • Location at which exception occurs [StackTrace]

After creating an exception object, the method handovers the object to the JVM.JVM will check whether the method contains any exception handling code or not? If the method doesn't contain code for exception handling then JVM terminates that method abnormally and removes the corresponding entry from the stack.

Then JVM identifies the caller method and checks whether caller methods contain any handling code or not, If the caller method also doesn't contain handling code, then JVM also terminates the caller methods abnormally and removes the corresponding entry from the stack.

This process will be continued until the main method and if the main method doesn't contain exception handling then JVM terminates the main method abnormally and removes the corresponding entry from the stack. Then JVM handovers responsibility of exception handling to default exception handling, which is the part of JVM.

public class Test {
    public static void main(String[] args) {
        doStuff();
    }

    private static void doStuff() {
        doMoreStuff();
    }

    private static void doMoreStuff() {
        System.out.println(10/0);
    }
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at ExceptionHandling.Test.doMoreStuff(Test.java:13)
	at ExceptionHandling.Test.doStuff(Test.java:9)
	at ExceptionHandling.Test.main(Test.java:5)

Default exception handling prints exception information in the following format and terminates program abnormally

Exception in thread "xxx" name of exception: Description StackTrace Note:


  • In a program, at least one method terminates abnormally then program termination is abnormal termination.

  • If all methods terminated normally then only program termination is normal termination.

Exception Hierarchy:


Throwable class acts as the root of the java exception hierarchy.
A throwable class defines two child classes:

  • Exception

  • Error

Exception:

Most of the time exceptions are caused by our program and these are recoverable. e.g. If your program required to read data from the remote file, at run time if the remote file is not available then we will get RunTimeException saying FileNotFoundException if FileNotFoundException exception occurs we can provide a local file and continue the rest of the program normally.


try{
   
   Read file from remote place

} catch (FileNotFoundException ex){

   Use local file and continue rest of the program normally

}

Error:

Most of the time errors are not caused by our program and these are due to lack of system resources. Errors are non-recoverable.

For e.g. If out of memory error occurs being a programmer we can't do anything and the program will be terminated abnormally. The system or server admin is responsible to increase heap memory.
If you have a function like these:

int foo()
{
    // more stuff
    foo();
}

Then foo() will keep calling itself until you get the StackOverflowError.


Checked vs Unchecked Exception:


The exceptions which are checked by the compiler for smooth execution of the program are called checked exceptions.
Here are the few other Checked Exceptions:

  • FileNotFoundException

  • SQLException

  • IOException

  • ClassNotFoundException

  • InvocationTargetException

If there is a chance of raising a checked exception then compulsory we should handle that checked exception(either by try-catch or by throws keywords) otherwise we will get a compile-time error.
The exceptions which are not checked by the compiler are called unchecked exceptions

Here are the few unchecked exception classes:

  • NullPointerException

  • ArrayIndexOutOfBoundsException

  • ArithmeticException

  • IllegalArgumentException

  • NumberFormatException

These exceptions are not caught at the compile time so we didn't get any report but it may result in complete failure of the application when it occurs during execution.
Note :

  • Every exception occurs at runtime only either it is checked or unchecked, there is no chance of occurring exception at compile time.

  • Runtime and its child classes, Error, and its child classes are unchecked, except this remaining are checked exceptions.

Fully Checked vs Partially Checked Exception:


A checked exception is said to be fully checked if and only if all its child classes are also checked.
e.g. IOException, IntteruptedException

A checked exception is said to be partially checked if and only if some of its child classes are unchecked
e.g. Exception, Throwable

Note: The only possible partially checked exception in java are exception and throwable.
Lets quick revision with few more examples :

  • IOException - checked (fully)

  • RunTimeException - unchecked

  • InterruptedException - checked(fully)

  • Error - unchecked

  • Throwable - checked(Partially)

  • AirthmeticException - unchecked

  • NullPointerException - unchecked

  • Exception - checked(Partially)

  • FileNotFoundException - checked(fully)


Customized exception handling using try-catch


Without try-catch :

public class Test1{
    public static void main(String[] args) {
        System.out.println("test1");
        System.out.println(10/0);
        System.out.println("test2");
    }
}
O/P : - 
test1
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at ExceptionHandling.Test1.main(Test1.java:6)

With try-catch :

public class Test1{
    public static void main(String[] args) {
        System.out.println("test1");
        try {
            System.out.println(10/0);
        }catch (ArithmeticException e){
            System.out.println(10/2);
        }
        System.out.println("test2");
    }
}
O/P : - 
test1
5
test2

It is highly recommended to handle exceptions.
The code which may raise an exception i.e. risky code, we have to define that code inside try block and corresponding handling code we have to define inside catch block


try{
	stm1;
	stm2;
	stm3;
}catch(Exception e){
	stm4;
}
stm5;

case1 : If there is no exception - 1,2,3,5 - Normal termination
case2: If exception raised at 2 and the corresponding catch block is matched - 1,4,5 - Normal Termination
case3: If exception raised at 2 and the corresponding catch block is not matched - 1, Abnormal Termination
case4: If exception raised at 4 or 5 then it is always abnormal termination

Note:

  1. Within the try block, if an exception occurred anywhere then rest of the try block won't be executed event though we handled that exception. Hence within the try block, we have to take risky code only and length of the try block should be as least as possible

  2. In addition, to try block there may be a chance of raising exception inside catch and finally blocks

  3. If any statement which is not part of the try block and raises an exception then it is always abnormal termination


Lets quick summarise what we learn in this post:

  • Whats is an exception?

  • How the runtime stack mechanism works in exception handling?

  • Default exception handling in java

  • Exception Hierarchy - Exception and Error

  • Difference between Checked vs Unchecked Exception

  • What is mean by fully checked and partially checked exception

  • Customized exception handling using try-catch

With this, we also came to the end of this article. In the next article, we would be learning Control flow in try-catch, Methods to print exception info, try with multiple catch blocks, etc.. Please let us know about your views and opinions in the comment section below. I hope you enjoyed this post. Please stay with us for more posts.
For more details on exception handling please refer Video

Related Posts:

  • Multithreading in Java | Part-1In this tutorial series, we are learning multithreading in Java. This is the first article in the series. Here we are going through the basic concept … Read More
  • Multithreading in Java | Part-2In this tutorial series, we are learning multithreading in Java. This is the second article in the series. In the first article, we learned about… Read More
  • Exception Handling in Java | Part-2This is the second post on a series of Exception Handling in Java. In this article, we will learn methods to print exception info, try with multiple c… Read More
  • Exception Handling in Java | Part-3This is the third post on a series of Exception Handling in Java. In this article, we will revise exception handling keywords, various possible compil… Read More
  • Apache Kafka In this tutorial, we are understanding about Apache Kafka. Apache Kafka is a highly scalable distributed messaging system. Kafka is useful where a la… Read More

0 comments:

Post a Comment