Exception Handling in java

In general, the term Exception means “a person or thing that is excluded from a general statement or does not follow a rule.” and Exception handling is a process of responding to the occurrence of the anomaly or exception.

Do you know professional programmers write more exception handling code instead of writing the core logic? Wonder what is the reason behind it?

Consider an example, code is written to control numerous functions/features of an airplane. In case there is an exception like heavy rain, storm, computer virus or any other environmental issues that can impact the smooth running to the plane so, these issues or exceptions should be considered and handled through exception handling mechanism in order to avoid the plane crash or such problem.

Along with developing the code to provide a feature in a plane the proper error handling code is also written to avoid any of the environmental mishappenings. The same is applicable to every product.

Exception handling in JAVA is same as above stated, a developer will build an application that can handle mistake done by users with Try/Catch block or may be using some other ways. The main purpose of Exception handling is to ensure the smooth execution of application and application should not break down by any exception or anomaly such as ClassNotFound, IO, SQL, Remote etc and any anomalies can be handled.

Types of Exception:

Oracle says there are three types of exceptions:

  • Checked Exception
  • Unchecked Exception
  • Error

Among which there are only two main exceptions: checked and unchecked, where an error is considered as unchecked throwable. The difference between unchecked exceptions and unchecked throwables is that your code shouldn’t throw an error and code will throw an error respectively.

Difference between checked and unchecked exceptions :

  • Checked Exception – The classes that extend a Throwable class in java except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time
  • Unchecked Exception – The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime
  • Error – Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc

Before proceeding forward let’s throw some light on types of errors

Types of Errors:

  • Compile Time/Syntax – Example: Missing, mis-spelling, using variable without declaration
  • Runtime – Example: Division By Zero, Invalid Conversion, Accessing an invalid index of an array
    • A runtime error results in an Exception
    • Whenever Exception occurs Java creates an Object of “Exception” or its derived class
    • Exception leads to abnormal termination of the program
    • Handling means making the user aware of the problem

Exception Hierarchy

Common scenarios where Exceptions may occur – There are given some scenarios where unchecked exceptions can occur, they are as follows:

  • A scenario where ArithmeticException occurs:

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;                       //ArithmeticException  

  • A scenario where NullPointerException occurs:

If we have a null value in any variable, performing any operation by the variable occurs a NullPointerException.

String s=null;  

System.out.println(s.length());  //NullPointerException  
  • A scenario where NumberFormatException occurs:

The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters, converting this variable into digit will occur NumberFormatException.

String s="abc";  

int i=Integer.parseInt(s);       //NumberFormatException  
  • Scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];  

a[10]=50;                       //ArrayIndexOutOfBoundsException

Internal working of java try-catch block:

The JVM firstly checks whether the Exception is handled or not. If Exception is not handled, JVM provides a default exception handler that performs the following tasks:

  • Prints out exception description
  • Prints the stack trace (Hierarchy of methods where the exception occurred)
  • Causes the program to terminate

But if an exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed

Try:

  • All statements that may result in an error are written within try
  • A method can have nested or multiple try blocks

Catch:

  • Every “try” should be followed by at least 1 catch block
  • Multiple catch blocks work like cases in switch only one will be executed depending on Exception generated
  • catch receives an argument of Exception or its derived class
  • The catch is conditional

Java finally block:

  • finally block is a block that is used to execute important code such as closing connection
  • It is always executed whether an exception is handled or not
  • finally block follows try or catch block
  • It does not receive any argument
  • finally is unconditional

Throw :

  • It is used to generate an Exception

Throws :

  • It is used to forward an Exception

Example 1 :

class Exception1 {
public static void main(String args[]) {
int a = 10, b = 0, c = 0;;
c = a / b;
System.out.println("Result : "  + c);
}
}

// Division by zero results in ArithmeticException

Example 2:

class Exception2 {
public static void main(String args[]) {
int a = 10, b = 0, c = 0;
try {
c = a / b;
}
catch(ArithmeticException e) {
System.out.println("Division by Zero.");
System.out.println(e.getMessage());
ae.printStackTrace();
}
System.out.println("Result : "  + c);
}
}

Example 3 :

class Exception3 {
public static void main(String args[]) {
int num = 0;
try {
num = Integer.parseInt(args[0]);
}
catch(NumberFormatException ne) {
System.out.println("Invalid Format.");
}
catch(ArrayIndexOutOfBoundsException ae) {
System.out.println("Invalid Index.");
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("Square : "+ Math.pow(num,2));
}
}

Find the working Example of Exception Handling on codedbug Github Repo

Most Frequently Asked Questions On Exception Handling

An Error indicates serious problems that an application should not try to catch. while An Exception indicates conditions that an application might want to catch.
The throws keyword is used to specify that a method may raise an exception during its execution while the throw keyword allows us to throw an exception object to interrupt the normal flow of the program.
final: Any variable declares along with final modifier then those variables treated as a final variable. Methods declared as final is not overridden. Final classes are not extended. While finally blocks are followed by a try or catch and they are compulsorily executable blocks. While in finalize( ) before an object is garbage collected, the garbage collector calls this finalize() method of the object. If that object having any connections with a database or anything, it removes the connections and calls finalize() of the object that destroy the object.
In Java 7, if you use a resource like input or output streams or any database connection logic you always need to close it after using. If it is not closed, it can throw exceptions so it has to be in a try & catch block.
Exceptions which are raised in the try block are handled in the catch block. If it is unable to handle that exception, it can re-throw that exception using throw keyword. It is called re-throwing an exception.