Exception is a condition due to which our program terminates abnormally.Exception causes our program to crash.
Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Exception handling is a mechanism used to describe what to do when something unexcepted happen.
The Java programming language provides two broad categories of exceptions:
Checked exceptions are those that the programmer is expected to handle in the program, and that arise from external conditions that can readily occur in a working program.
Unchecked exceptions might arise from conditions that represent bugs, or situations that are considered generally too difficult for a program to handle reasonably. Exceptions that arise from a category of situations that probably represent bugs are called runtime exceptions.
Let us understand the concept of exception by using the example.
1 public class AddArguments { 2 public static void main(String args[]) { 3 int sum = 0; 4 for ( int i = 0; i < args.length; i++ ) { 5 sum += Integer.parseInt(args[i]); 6 } 7 System.out.println("Sum = " + sum); 8 } 9 } Condition 1: java AddArguments 1 2 3 4 Sum = 10
Condition 2: This program fails if any of the arguments are not integers: java AddArguments 1 two 3.0 4
Exception in thread "main" java.lang.NumberFormatException: For input string: "two"at java.lang.NumberFormatException.forInputString(NumberFormat Exception.java:48) at java.lang.Integer.parseInt(Integer.java:447) at java.lang.Integer.parseInt(Integer.java:497) at AddArguments.main(AddArguments.java:5)
Type 1. try { ------->try block is a block where exception might arrise } catch(Exception e) { ------->catch block is a block where exception is handled } Type 2. try { } catch(ArithmaticException ae) { } catch(IOException ioe) { } catch(Exception e) { } Type 3. try { } catch(Exception e) { } finally { ------->finally block executes wheather exception occur or not. }
import java.io.*; public class ExcepTest { public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } }
The finally clause defines a block of code that always executes, regardless of whether an exception is thrown.
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"); } } }