Wednesday, 9 October 2019

Java Tutorials | What is Exception Handling?

An exception is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program terminates abnormally, which is not recommended.  The mechanism to handle such scenarios known as Exception Handling.

Few exceptions are NullPointerException, ClassNotFoundException, IOException, SQLException, RemoteException etc.

Advantage of Exception Handling
The main advantage of exception handling is to maintain the normal flow of the application. See the scenario below.

statement 1; 
statement 2; 
statement 3;//exception occurs 
statement 4; 
statement 5;

Suppose there are 5 statements in Java program and there occurs an exception at statement 3, the rest of the code will not be executed i.e. statement 4 and 5 will not be executed. However, we can be executed the rest of the statement by exception handling.

Java Exception Handling Keywords
Java provides specific keywords for exception handling purposes. See the list below.

try-catch – try-catch block is used to handle exception in code. try is the start of the block and catch is at the end of try block to handle the exceptions. try block can have multiple catch blocks and try-catch block can be nested also. catch block requires a parameter that should be of type or subtype Exception.

try-catch example

public class TryCatchExample {
      public static void main(String[] args) {
            try {
                  int data = 50 / 0;// may throw exception
                  System.out.println(data);
            } catch (ArithmeticException e) {// handling the exception
                  System.err.println(e);
            }
            System.out.println("rest of the code");
      }
}

try-multiple catch example

public class TryCatchExample {
      public static void main(String[] args) {
            try {
                  int data = 50 / 0;// may throw exception
                  System.out.println(data);
            } catch (ArithmeticException e) {// handling the exception
                  System.err.println(e);
            } catch (NullPointerException e) {// handling the exception
                  System.err.println(e);
            }

            System.out.println("rest of the code");
      }
}

try-multiple catch Java 7 example

After Java 7 release, we can club multiple catches using pipeline separator.

public class TryCatchExample {
      public static void main(String[] args) {
            try {
                  int data = 50 / 0;// may throw exception
                  System.out.println(data);
            } catch (ArithmeticException | NullPointerException e) {// handling the exception
                  System.err.println(e);
            }

            System.out.println("rest of the code");
      }
}

finally – finally block is optional and can be used only with try or try-catch block. Since exception halts the process of execution, the program might have some resources open that will not get closed, so it can be closed in finally block as finally block executed always, whether an exception occurred or not.

class TestFinallyBlock {
      public static void main(String args[]) {
            try {
                  int data = 25 / 0;
                  System.out.println(data);
            } catch (NullPointerException e) {
                  System.out.println(e);
            } finally {
                  System.out.println("finally block is always executed");
            }
            System.out.println("rest of the code...");
      }
}
Output:
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
      at com.algorithmforum.gson.TestFinallyBlock.main(TestFinallyBlock.java:6)

throw – If any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime it might require to generate exception explicitly in code, for example in user authentication, the program should throw an exception to the client if the password is null. throw keyword is used to throw an exception to the runtime to handle it.

class InvalidAge extends RuntimeException {
      private static final long serialVersionUID = 1L;
      public InvalidAge(String string) {
            super(string);
      }
}

public class TestThrowKeyword {
      private static void validate(int age) {
            if (age < 18) {
                  throw new InvalidAge("not valid");
            } else {
                  System.out.println("welcome to vote");
            }
      }

      public static void main(String args[]) {
            validate(13);
            System.out.println("rest of the code...");
      }
}
Output:
Exception in thread "main" com.algorithmforum.gson.InvalidAge: not valid
      at com.algorithmforum.gson.TestThrowKeyword.validate(TestThrowKeyword.java:15)
      at com.algorithmforum.gson.TestThrowKeyword.main(TestThrowKeyword.java:22)

throws – When the program is throwing an exception in a method and no need to handle it, throws keyword need to use in method signature to let the caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to its caller method using throws keyword. Multiple exceptions can provide in the throws clause and it can be used with main() method also.

class InvalidAge extends Exception {
      private static final long serialVersionUID = 1L;
      public InvalidAge(String string) {
            super(string);
      }
}

public class TestThrowKeyword {

      private static void validate(int age) throws InvalidAge {
            if (age < 18) {
                  throw new InvalidAge("not valid");
            } else {
                  System.out.println("welcome to vote");
            }
      }

      public static void main(String args[]) throws InvalidAge {
            validate(13);
            System.out.println("rest of the code...");
      }
}
Related Posts Plugin for WordPress, Blogger...