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;
[Link]("Result = " + c);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + e);
} finally {
[Link]("Finally block executed.");
}
}
}
Output:
Exception caught: [Link]: / 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) {
[Link]("Caught Exception: " + e);
}
}
}
Output:
Caught Exception: [Link]: 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");
}
[Link]("You are eligible to vote");
}
}
Output:
Exception in thread "main" [Link]: Not eligible to vote
Example 4: throws Keyword and IOException
import [Link].*;
public class Ex4_Throws {
static void readFile() throws IOException {
FileReader fr = new FileReader("[Link]");
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
[Link]();
Exception Handling in Java (J2SDK 1.4.0 Compatible)
public static void main(String args[]) {
try {
readFile();
} catch (IOException e) {
[Link]("Caught IOException: " + e);
}
}
}
Output:
Caught IOException: [Link]: [Link] (The system cannot find the file specified)
Example 5: finally Block Always Executes
public class Ex5_Finally {
public static void main(String args[]) {
try {
[Link]("Inside try block.");
} catch (Exception e) {
[Link]("Inside catch block.");
} finally {
[Link]("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