Tuesday, February 11, 2020

try catch exception handling

Exception Handling In Java (try-catch blocks)

Exceptions can be handled by five keywords

  • try
  • catch
  • throws
  • throw
  • finally

The “try-catch” block

A try-catch block is the most commonly used exception handling technique by Java programmers. Any part of the code that can generate exception should be kept inside try block, and exception should be handled in the catch block. The corrective action in case of an exception should be kept in the catch block. However, a single block of code can raise more than one exception We can specify two or more catch clauses followed by the try block.

public class EceptionDemo {

      public static void main(String[] args) {
            System.out.println("Statement 1");
            int a=5;
            try {       // try block
                  // possibility of an Exception starts
            System.out.println("div "+a/0); //Uncheched exception
            }catch(ArithmeticException ae) //catch block
            System.out.println("Statement 2");

Statement 1
java.lang.ArithmeticException: / by zero at com.miet.main.EceptionDemo.main(EceptionDemo.java:10)
Statement 2

The Catch clauses are executed in order occurrence. If one is executed(After match) others are bypassed and the execution after try-catch blocks starts. In case of using multiple catch clauses, the subclass exception must appear before the superclass. This is done because if superclass Exception comes first then catch block having subclass will be unreachable. This will apparently manifest unreachable code error.

Nested try -catching blocks

Try statements can be nested within another try block. If inner try bock doesn't have a catch block than catch block of outer try block will handle the exception. This continues until one catch block doesn’t handle the Exception or till all the try blocks are exhausted. If no catch matches than Java runtime handle the exception.

public class EceptionDemo {

      public static void main(String[] args) {
            System.out.println("Start Statement");
            System.out.println("nested try catch");
            try {
                  System.out.println("inside try before exception");
                  try {
                        System.out.println("within nested try");
                  catch (ArithmeticException e) {
                        System.out.println("Subclass Exception");
            catch (Exception e) {
                  System.out.println("Super class Exception");
            System.out.println("End Statement");

OR we can understand the execution of nested try-catch as

Video Tutorial