Is it possible to resume java execution after exception occurs?

Java 8Object Oriented ProgrammingProgramming

An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.

There are two types of exceptions in Java.

  • Unchecked Exception − An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
  • Checked Exception − A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions.

Resuming the program

When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program.

Example

import java.io.File;
import java.io.FileInputStream;
public class Test {
   public static void main(String args[]){
      System.out.println("Hello");
      try{
         File file =new File("my_file");
         FileInputStream fis = new FileInputStream(file);
      }catch(Exception e){
         System.out.println("Given file path is not found");
      }
   }
}

Output

Given file path is not found

When a run time exception occurs You can handle runtime exceptions and avoid abnormal termination but, there is no specific fix for runtime exceptions in Java, depending on the exception, type you need to change the code.

Example

public class ExceptionExample {
   public static void main(String[] args) {
      //Creating an integer array with size 5
      int inpuArray[] = new int[5];
      //Populating the array
      inpuArray[0] = 41;
      inpuArray[1] = 98;
      inpuArray[2] = 43;
      inpuArray[3] = 26;
      inpuArray[4] = 79;
      //Accessing index greater than the size of the array
      System.out.println( inpuArray[3]);
   }
}

Output

26
raja
Published on 07-Aug-2019 10:56:45
Advertisements