Exception Handling in Java (J2SDK 1.4.
0 Compatible)
What is Exception Handling?
Exception handling in Java allows you to handle run-time errors (exceptions) so that normal execution of the program
can continue without abrupt termination.
Syntax (Java 1.4 Style)
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute (optional)
}
Types of Exceptions
Checked (Compile-time): IOException, FileNotFoundException
Unchecked (Runtime): ArithmeticException, NullPointerException
Example 1: ArithmeticException
public class Ex1_Arithmetic {
public static void main(String args[]) {
try {
int a = 10, b = 0;
int c = a / b;
System.out.println("Result = " + c);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block executed.");
}
}
}
Output:
Exception caught: java.lang.ArithmeticException: / by zero
Finally block executed.
Example 2: ArrayIndexOutOfBoundsException
Exception Handling in Java (J2SDK 1.4.0 Compatible)
public class Ex2_Array {
public static void main(String args[]) {
try {
int arr[] = new int[3];
arr[5] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught Exception: " + e);
}
}
}
Output:
Caught Exception: java.lang.ArrayIndexOutOfBoundsException: 5
Example 3: throw Keyword
public class Ex3_Throw {
public static void main(String args[]) {
int age = 16;
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
System.out.println("You are eligible to vote");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: Not eligible to vote
Example 4: throws Keyword and IOException
import java.io.*;
public class Ex4_Throws {
static void readFile() throws IOException {
FileReader fr = new FileReader("data.txt");
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
fr.close();
Exception Handling in Java (J2SDK 1.4.0 Compatible)
public static void main(String args[]) {
try {
readFile();
} catch (IOException e) {
System.out.println("Caught IOException: " + e);
}
}
}
Output:
Caught IOException: java.io.FileNotFoundException: data.txt (The system cannot find the file specified)
Example 5: finally Block Always Executes
public class Ex5_Finally {
public static void main(String args[]) {
try {
System.out.println("Inside try block.");
} catch (Exception e) {
System.out.println("Inside catch block.");
} finally {
System.out.println("Inside finally block.");
}
}
}
Output:
Inside try block.
Inside finally block.
Java 1.4 Key Notes
try : To define a block that might cause error
catch : To handle the specific exception
finally : Optional block, always executes
throw : To explicitly throw an exception
throws : To declare exceptions in method header