Exception Handling in Java

Exception Handling in Java Definition -

Exception in java is a run-time error that cause due to logical mistake because of wrong input given by user. Technically exception is a object instance of throwable or its one of sub-classes.

When exception raise programe execution terminated abnormally, abnormal means the statement placed after exception causing statement will not be executed.

Example -

You went to ATM center to withdraw money from account, in your bank account you have 500 RS and you are trying to withdraw 1000 RS then atm machine will display "insufficient fund in you account" message that is user understandable message but internally it throws InsufficientFundException. There is no predefined exception with name InsufficientFundException but this can be custom exception.

public class StringBufferDemo {
    public static void main(String[] args) {

        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);
        int c = a/b;
        
        System.out.println("Result :"+c);
    }
}

Input- 10 0

Output- Exception in thread “main” java.lang.ArithematicException.

The above java exception message is not understandable by end-user because it is java programmer related message. It is programmer responsibility to print user understandable message i.e pure English message.

For this purpose we must catch exception in the program itself, we should not allow it to propagate to JVM. After catching exception we must print user a message to take correct values from end user.


// Try With Catch
try
{
...
}
catch(Exception e)
{
}

// Try With Catch And Finally
try
{
...
}
catch(Exception e)
{
...
}
finally
{
...
}

// Try With Only Finally
try
{
...
}
finally
{
...
}

Note-  A try can have multiple Catch blocks but it can have only one finally block.

public class Exception {

    public static void main(String[] args) {

       try {

           int a = Integer.parseInt(args[0]);

           int b = Integer.parseInt(args[1]);

           int c = a/b;

           System.out.println("Result :"+c);

       }catch (ArithmeticException ae) {

           System.out.println("Java Exception Do not pass second value as 0");

       }

    }

}
Input- 10, 0
Output- Java Exception Do not pass second value as 0

Hierarchy of Java Exception Classes-

exception handling in java

When an exception can occur ?

Java Exception can occur at run-time (known as run-time exceptions) as well as at compile-time (known as Compile-time exceptions).

Type of Exception in Java ?

  • Checked Exception- Directly subclass of exception are checked exception, these exception are called pure checked exception.
  • Unchecked Exception- Error & Run-time Error are unchecked exception it is optional to report.

Exception Rule -

1. Catch block parameter type should be Throwable & any of its subclass if we use other type it lead compile time error incompatible type.

try {
}

catch(ArithmeticException ae){}

catch(String s){}  //Not allowed will throw exception

2. We should not duplicate catch block & also we should not place parent class parameter catch block before child class parameter catch block. It leads to Compile Time Error Exception has already been caughttry {

throw new ArithematicExcpetion();

throw new ArrayIndexOutOfBoundException();

}

Catch(ArithmeticException ae) { }         Catch(ArrayIndexOutOfBoundException aoi){ }

3. After throw keyword we should not place any java statement directly it leads Compiler Error unreachable statement because throw keyword is a transfer statement.class A {

void m1() {

System.out.println(“hello”);

throw new ArithmeticException();

System.out.println(“JavaTechWorld”); //C.E Unreachable Exception

}

}

4. After throw keyword we should only place throwable calss object or any of its subclass object. if we place normal object compiler throws incompatible type error.

 throw new ArithmeticException(); //correct

 throw "abc"; //C.E Incompatible type.

5. if we are throwing a checked exception using throw keyword or receiving a checked exception by method call we must handle that exception eithe by catching using try-catch or by reporting using throws keyword else it leads C.E unreported exception must be caught or declared to be thrown.

 class Test {

                   void m1() {

                           throw new ClassNotFoundException(); //C.E

                     }

            }

           class Test {

                    void m1() {

                          try {

                                throw new ClassNotFoundException();

                          }

                          catch(ClassNotFoundException cnfe) {  //correct way

                                   cnfe.printStackTrace();

                          }

                    }

            }

6. We should not write catch block for checked exception without throwing it from its corresponding try block it leads C.E "Exception never thrown from corresponding try block"

   try {
           }
           catch(ArithematicException ae) {
           }
           catch(ClassNotFoundException cnfe) { /*checked exception not allowed with                                                                                         throwing from its corresponding try block*/
           }

7. We should not use throw keyword in method prototype & throws keyword in method body leads C.E ';' expected & illegal start of expression.

8.The variable declare in try-catch-finally can not be access from outside of these block because the variable become local to that block & it is destroy after block execution.

Throws/Throw Keyword -

Sometimes we explicitly want to create exception object and then throw it to stop the normal processing of the program. throw keyword is used to throw exception to the run-time to handle it.

When we are throwing any checked exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.

The finally Keyword -

Typically, we expect the try/catch block to do something or handle exceptions that occurs, then continues the flow of code. What happens if the catch block throws an exception? It is okay to add an other try/catch block inside the catch block. Yet, the code will look confusing if there are several nested catch blocks.
Fortunately, Java allows you to specify a block of code that should be executed whatever happens inside the try/catch block. This block is called the finally  block.

In other words, a finally block help ensure that however the method exit, some cleanup code will be executed.

Example -

public class FinallyExample {
    public static void main(String args[]){
        try{
            int n=30/5;
            System.out.println(n);
        }
        catch(NullPointerException e){System.out.println(e);}
        finally{System.out.println("finally block in java");}
        System.out.println("exception in java -> rest of the code...");
    }

Creating custom checked exception -

Creating your own exception class in java is very simple. All you need to do is just extend "Exception" class or its sub-classes for checked custom exception and extend RuntimeException or its sub-classes for unchecked custom exception.

Example -

class MyCustomException extends Exception {
    MyCustomException(String s) {
        super(s);
    }
}

2 thoughts on “Exception Handling in Java

    • Hi Yogesh,
      Thanks for your query. Below is the answer.

      For below cases finally won’t be called these are:

      1.In case of you invoke System.exit();
      2.In case of JVM crashes first.
      3.If there is an infinite loop (or some other non-interruptable, non-terminating statement) in the try block.

      I recommend you to use System.exit(); to terminate finally block process else remove finally block if it not required for better coding practice.

Leave a Comment

%d bloggers like this: