Java- Exception Handling In Java With Example Program - JavaTechWorld

Wednesday, 24 May 2017

Java- Exception Handling In Java With Example Program

    0

Exception Handling in Java- Exception in java is a runtime 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 subclasses.
When exception raise programme execution terminated abnormally, abnormal means the statement placed after exception causing statement will not be executed.

Example-

We are going to atm to withdraw money suppose in your account you have 500rs but your withdraw amount is 1000 then atm machine will display insufficient fund in your account 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.

Exception Handling Syntax in Java Programming-

// 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 hierarchy in java

When an exception can occur?

Java Exception can occur at runtime (known as runtime 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 & Runtime Error are unchecked exception it is optional to report.
Exception Rule-
  • ·    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

  • ·    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 caught
try {
throw new ArithematicExcpetion();
throw new ArrayIndexOutOfBoundException();
 }
         Catch(ArithmeticException ae) { }
         Catch(ArrayIndexOutOfBoundException aoi){ }
  • ·    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 Unreacble Exception
                }
            }

  • After throw keyword we should only place throwable calss object or any of its subclass object. if we place normal object compiler throws imcopatible type error.
         throw new ArithmeticException(); //correct
         throw "abc"; //C.E Incompatible type
  • if we are throwing a checked exception using throw keyworld 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();
                          }
                    }
            }

  • 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*/
           }  

  • We should not use throw keyword in method prototype & throws keyword in method body leads C.E ';' expected & illegal start od expression.
  • The variable declare in try-catch-finally can not be acess from outside of these block because the variable become local to that block & it is destroy after block execution.
The 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 runtime 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 subclasses for checked
custom exception and extend RuntimeException or its subclasses for unchecked
custom exception.
Example-
class MyCustomException extends Exception {
    MyCustomException(String s) {
        super(s);
    }
}

© 2014 JavaTechWorld. Designed by Bloggertheme9
Powered by Blogger.