An exception is an issue (run time error) occurred during the execution of a program. For understanding purpose let us look at it in a different manner.
Generally, when you compile a program, if it gets compiled without a .class file will be created, this is the executable file in Java, and every time you execute this .class file it is supposed to run successfully executing each line in the program without any issues. But, in some exceptional cases, while executing the program, JVM encounters some ambiguous scenarios where it doesn’t know what to do.
Here are some example scenarios −
Generally, when exception occurs the program terminates abruptly at the line that caused exception, leaving the remaining part of the program unexecuted. To prevent this, you need to handle exceptions.
To handle exceptions Java provides a try-catch block mechanism.
A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code.
try { // Protected code } catch (ExceptionName e1) { // Catch block }
When an exception raised inside a try block, instead of terminating the program JVM stores the exception details in the exception stack and proceeds to the catch block.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in the try block it is passed to the catch block (or blocks) that follows it.
If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
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"); } } }
Given file path is not found
The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); }finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } }
Exception thrown : java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed