0
Sponsored Links


Ad by Google
After completion of BlockingQueue Tutorial and Hibernate Tutorial now starting with very popular topic of core java called Exception. And in this tutorial, I will try to explain what is Exception and What are the different types of Exceptions in java including your own custom exception, and how to use them.

What is Exception in java?
An exception is an exceptional event, which occurs during the execution of program and interrupt the normal flow of the running program.
Like celebrating new year night with dancing on a floor and suddenly audio woofer stopped working.

As soon as an error occurs in your method, it' will create an object of Exception class and throwing that exception to the Run-time system. The Run-time system, who will find the appropriate handler(block of code to handle the exception) for the exception from the call stack of the method. The Run-time system will scan all the method in call stack until an appropriate handler is found, once appropriate exception handler is found that means catches the exception. If not found the appropriate handler in the call stack than, Run-time system will terminate the program.

Here is the call stack image -
From the image -
main method is calling m1() with handling an exception and m1() is calling m2() and m2() is calling m3() method where exception is thrown, this is known as call stack where run-time system will scan all the these methods to find the appropriate handler, which is in m1() method.
Exception Handling Requirement -
The exception handling requirement says, if the code that might throw an exception must be enclosed with try-catch block or throws the exceptions and these can be achieved using below exception handling keywords,
try - The try block, where you must need to enclosed the code that might  thrown an exception, for example parsing String to int might throw NumberFormatException. So parsing line of code must be placed inside try block, like below code example.
try {
  return Integer.parseInt(str);
    }
catch - The catch block is an exception handler, that handles the type of exception specified in it's argument, and it is associated with try block, possible that multiple catch block is associated with a single try block.
The catch block contains the code that is to be executed, if any exception is encountered in try block, below is the syntax of try-catch block -
try {
  return Integer.parseInt(str);
 } catch (NumberFormatException e) {
  e.printStackTrace();
 }
                                    or
try {
  return Integer.parseInt(str)/0;
 } catch (NumberFormatException |ArithmeticException e) {
  //TODO: do what ever wants to.
 }
finally - The finally block will always executed and used with try-finally block or try-catch-finally block. The finally bock will executed irrespective of exception in try block or not.
Syntax -
try {
   return Integer.parseInt(str) / 0;
  } finally {
   System.out.println("Always executed");
  }
                                                      or
try {
   return Integer.parseInt(str) / 0;
  } catch (NumberFormatException | ArithmeticException e) {
   // TODO: do what ever wants to.
  } finally {
   System.out.println("Always executed !");
  }

try-with-resources - The try statement declared with one or more resources, A resource is an object that must be closed after the completion of the program. For example after reading a file you must need to close the file, if you are using try with resource than you no need to worry about the closing/releasing the resources, it will automatically done by JVM.
Syntax -
try (FileReader f = new FileReader("filePath")) {
   //No need to call f.close();
  } catch (IOException e) {
   // TODO: do what ever wants to.
  }
throws - The throws keyword used with a method, when a method is throwing an exception but instead of handling that exception, we simply let the caller to handle these exceptions by simply throwing the exceptions.
Syntax to use -
public static int getNum(String str) throws NumberFormatException {

  return Integer.parseInt(str);
 }
throw - The throw keyword is used to throw a specific exception by creating an instance of that Exception, sometime you handled a exception and based on the exception you create an instance of another Exception and throw it to the caller. like when user email ID format is wrong than we simply throw a custom exception as EmailFormatException.
Syntax to use -
public static int getNum(String str) {
  throw new IllegalArgumentException("Not a valid number");
 }
Now lets see the complete example of exception handling.
ExceptionExample .java
package com.javamakeuse.poc;

public class ExceptionExample {
 public static int getNum(String str) {
  try {
   return Integer.parseInt(str) / 0;
  } catch (NumberFormatException | ArithmeticException e) {
   e.printStackTrace();
  } finally {
   System.out.println("Always executed !");
  }
  return -1;
 }

 public static void main(String[] args) {
  System.out.println(getNum("10"));
 }
}

OUT PUT
java.lang.ArithmeticException: / by zero
at com.javamakeuse.poc.ExceptionExample.getNum(ExceptionExample.java:6)
at com.javamakeuse.poc.ExceptionExample.main(ExceptionExample.java:16)
Always executed !
-1

Types of Exception in java
We have lots of built in exception classes in java, mostly in java.lang and java.io packages. And these exceptions are categorized into three different category and parent of all the exception class is Throwable and these are -
  1. Checked Exceptions (Read more about Checked Exception)
  2. Runtime Exceptions (Read more about Runtime Exception)
  3. Error (What is Error in java)
The java.lang.RuntimeExceptions and java.lang.Error collectively known as UN-Checked Exception in java.
Below is  the complete design of Exception Hierarchy -


That's it for now. In my next post, I will try to explain different types of Exceptions.

Sponsored Links

0 comments:

Post a Comment