Exceptions
Try-Catch
Handling Exceptions
Your program reads a file that might not exist. Without exception handling, it crashes. With try-catch, you can detect the error and respond gracefully - show a message, try a different file, or use default data.
Basic try-catch
Catch and handle an exception.
// Basic Try-Catch: Division by Zero
public class BasicTryCatch {
public static void main(String[] args) {
System.out.println("=== Basic Try-Catch ===\n");
// Without try-catch - would crash
// int result = 10 / 0; // ArithmeticException!
// With try-catch - handle gracefully
int numerator = 10;
int denominator = 0;
try {
System.out.println("Attempting division...");
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error caught!");
System.out.println("Exception type: " + e.getClass().getName());
System.out.println("Message: " + e.getMessage());
}
System.out.println("\nProgram continues normally...");
// Demonstrate successful division
System.out.println("\n--- Successful Division ---");
int a = 20;
int b = 4;
try {
int result = a / b;
System.out.println(a + " / " + b + " = " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
// Multiple attempts in one try block
System.out.println("\n--- Multiple Operations ---");
int[] numbers = {10, 5, 0, 2};
int dividend = 100;
for (int num : numbers) {
try {
int result = dividend / num;
System.out.println(dividend + " / " + num + " = " + result);
} catch (ArithmeticException e) {
System.out.println(dividend + " / " + num + " = Error (division by zero)");
}
}
System.out.println("\n=== Key Points ===");
System.out.println("""
1. try block contains risky code
2. catch block handles the exception
3. Specify exception type to catch
4. e.getMessage() gives error details
5. Program continues after catch block
""");
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// Basic Try-Catch: Division by Zero
public class BasicTryCatch {
public static void main(String[] args) {
System.out.println("=== Basic Try-Catch ===\n");
// Without try-catch - would crash
// int result = 10 / 0; // ArithmeticException!
// With try-catch - handle gracefully
int numerator = 10;
int denominator = 2;
try {
System.out.println("Attempting division...");
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error caught!");
System.out.println("Exception type: " + e.getClass().getName());
System.out.println("Message: " + e.getMessage());
}
System.out.println("\nProgram continues normally...");
// Demonstrate successful division
System.out.println("\n--- Successful Division ---");
int a = 20;
int b = 4;
try {
int result = a / b;
System.out.println(a + " / " + b + " = " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
// Multiple attempts in one try block
System.out.println("\n--- Multiple Operations ---");
int[] numbers = {10, 5, 0, 2};
int dividend = 100;
for (int num : numbers) {
try {
int result = dividend / num;
System.out.println(dividend + " / " + num + " = " + result);
} catch (ArithmeticException e) {
System.out.println(dividend + " / " + num + " = Error (division by zero)");
}
}
System.out.println("\n=== Key Points ===");
System.out.println("""
1. try block contains risky code
2. catch block handles the exception
3. Specify exception type to catch
4. e.getMessage() gives error details
5. Program continues after catch block
""");
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
numerator ← 10, denominator ← 0
3public class BasicTryCatch {4 public static void main(String[] args) {5 System.out.println("=== Basic Try-Catch ===\n");67 // Without try-catch - would crash //?without_try_catch8 // int result = 10 / 0; // ArithmeticException!910 // With try-catch - handle gracefully //?with_try_catch11 int numerator→ 10 = 10; //?numerator12 int denominator→ 0 = 0; //?denominator13 //@denominator=0, 2output=== Basic Try-Catch ===try
15try { //?try_block16 System.out.println("Attempting division..."); //?before_division17 int result = numerator10 / denominator0; //?division_attempt18 System.out.println("Result: " + result); //?after_divisionoutputAttempting division...catch (ArithmeticException e)
18 System.out.println("Result: " + result); //?after_division19} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_block20 System.out.println("Error caught!"); //?error_caught21 System.out.println("Exception type: " + e.getClass().getName()); //?exception_type22 System.out.println("Message: " + e.getMessage()); //?exception_message23}outputError caught! Exception type: java.lang.ArithmeticException Message: / by zeroa ← 20, b ← 4
25System.out.println("\nProgram continues normally..."); //?program_continues2627// Demonstrate successful division //?successful_demo28System.out.println("\n--- Successful Division ---");2930int a→ 20 = 20; //?var_a31int b→ 4 = 4; //?var_boutput Program continues normally... --- Successful Division ---result ← 5
33try { //?try_success34 int result→ 5 = a20 / b4; //?division_success35 System.out.println(a20 + " / " + b4 + " = " + result5); //?print_success36} catch (ArithmeticException e) { //?catch_successoutput20 / 4 = 5dividend ← 100
40// Multiple attempts in one try block //?multiple_attempts41System.out.println("\n--- Multiple Operations ---");4243int[] numbers = {10, 5, 0, 2}; //?numbers_array44int dividend→ 100 = 100; //?dividendoutput --- Multiple Operations ---for (int num : numbers)
pass 1 of 446for (int num10 : numbers) { //?loop_numbers47 try { //?try_loopAll 4 passes — pass 1 is the card above pass numedividend1 10 — — 2 5 — — 3 0 java.lang.ArithmeticException: / by zero 100 4 2 — — result ← 10
pass 1 of 446for (int num : numbers) { //?loop_numbers47 try { //?try_loop48 int result→ 10 = dividend100 / num10; //?division_loop49 System.out.println(dividend100 + " / " + num10 + " = " + result10); //?print_loop50 } catch (ArithmeticException e) { //?catch_loopoutput100 / 10 = 10All 4 passes — pass 1 is the card above pass numeresult1 10 — 10 2 5 — 20 3 0 java.lang.ArithmeticException: / by zero — 4 2 — 50 catch (ArithmeticException e)
49 System.out.println(dividend + " / " + num + " = " + result); //?print_loop50} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_loop51 System.out.println(dividend100 + " / " + num0 + " = Error (division by zero)"); //?error_loop52}output100 / 0 = Error (division by zero)System.out.println(" === Key Points ===");
55 System.out.println("\n=== Key Points ===");56 System.out.println("""57 1. try block contains risky code58 2. catch block handles the exception59 3. Specify exception type to catch60 4. e.getMessage() gives error details61 5. Program continues after catch block62 """);63}output === Key Points === 1. try block contains risky code 2. catch block handles the exception 3. Specify exception type to catch 4. e.getMessage() gives error details 5. Program continues after catch block
numerator ← 10, denominator ← 2
3public class BasicTryCatch {4 public static void main(String[] args) {5 System.out.println("=== Basic Try-Catch ===\n");67 // Without try-catch - would crash8 // int result = 10 / 0; // ArithmeticException!910 // With try-catch - handle gracefully11 int numerator→ 10 = 10;12 int denominator→ 2 = 2;output=== Basic Try-Catch ===result ← 5
14try {15 System.out.println("Attempting division...");16 int result→ 5 = numerator10 / denominator2;17 System.out.println("Result: " + result5);18} catch (ArithmeticException e) {outputAttempting division... Result: 5a ← 20, b ← 4
24System.out.println("\nProgram continues normally...");2526// Demonstrate successful division27System.out.println("\n--- Successful Division ---");2829int a→ 20 = 20;30int b→ 4 = 4;output Program continues normally... --- Successful Division ---result ← 5
32try {33 int result→ 5 = a20 / b4;34 System.out.println(a20 + " / " + b4 + " = " + result5);35} catch (ArithmeticException e) {output20 / 4 = 5dividend ← 100
39// Multiple attempts in one try block40System.out.println("\n--- Multiple Operations ---");4142int[] numbers = {10, 5, 0, 2};43int dividend→ 100 = 100;output --- Multiple Operations ---for (int num : numbers)
pass 1 of 445for (int num10 : numbers) {46 try {All 4 passes — pass 1 is the card above pass numedividend1 10 — — 2 5 — — 3 0 java.lang.ArithmeticException: / by zero 100 4 2 — — result ← 10
pass 1 of 445for (int num : numbers) {46 try {47 int result→ 10 = dividend100 / num10;48 System.out.println(dividend100 + " / " + num10 + " = " + result10);49 } catch (ArithmeticException e) {output100 / 10 = 10All 4 passes — pass 1 is the card above pass numeresult1 10 — 10 2 5 — 20 3 0 java.lang.ArithmeticException: / by zero — 4 2 — 50 catch (ArithmeticException e)
48 System.out.println(dividend + " / " + num + " = " + result);49} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) {50 System.out.println(dividend100 + " / " + num0 + " = Error (division by zero)");51}output100 / 0 = Error (division by zero)System.out.println(" === Key Points ===");
54 System.out.println("\n=== Key Points ===");55 System.out.println("""56 1. try block contains risky code57 2. catch block handles the exception58 3. Specify exception type to catch59 4. e.getMessage() gives error details60 5. Program continues after catch block61 """);62}output === Key Points === 1. try block contains risky code 2. catch block handles the exception 3. Specify exception type to catch 4. e.getMessage() gives error details 5. Program continues after catch block
Code that might fail goes in try. Error handling goes in catch.
Catch array bounds exception
Handle accessing invalid array indices.
// Array Index Out of Bounds Exception
public class ArrayBounds {
public static void main(String[] args) {
System.out.println("=== Array Bounds Exception ===\n");
// Create an array
String[] fruits = {"Apple", "Banana", "Cherry"};
System.out.println("Array: [Apple, Banana, Cherry]");
System.out.println("Valid indices: 0, 1, 2");
System.out.println("Length: " + fruits.length);
// Access valid index
System.out.println("\n--- Valid Access ---");
try {
String fruit = fruits[1];
System.out.println("fruits[1] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
// Access invalid index (too high)
System.out.println("\n--- Invalid Access (index too high) ---");
try {
String fruit = fruits[5];
System.out.println("fruits[5] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index 5 out of bounds");
System.out.println("Message: " + e.getMessage());
}
// Access invalid index (negative)
System.out.println("\n--- Invalid Access (negative index) ---");
try {
String fruit = fruits[-1];
System.out.println("fruits[-1] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Negative index");
System.out.println("Message: " + e.getMessage());
}
// Safe access pattern
System.out.println("\n--- Safe Access Pattern ---");
int[] indicesToTry = {0, 2, 5, -1, 1};
for (int index : indicesToTry) {
try {
String fruit = fruits[index];
System.out.println("fruits[" + index + "] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("fruits[" + index + "] = Invalid index!");
}
}
// Alternative: Check before accessing
System.out.println("\n--- Check Before Access ---");
int requestedIndex = 10;
if (requestedIndex >= 0 && requestedIndex < fruits.length) {
System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]);
} else {
System.out.println("Index " + requestedIndex + " is out of bounds (0-" + (fruits.length - 1) + ")");
}
System.out.println("\n=== Key Points ===");
System.out.println("""
1. Arrays have fixed size (0 to length-1)
2. Invalid index throws ArrayIndexOutOfBoundsException
3. Both too high AND negative indices are invalid
4. Can catch and handle, or check bounds first
5. getMessage() shows the invalid index number
""");
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// Array Index Out of Bounds Exception
public class ArrayBounds {
public static void main(String[] args) {
System.out.println("=== Array Bounds Exception ===\n");
// Create an array
String[] fruits = {"Apple", "Banana", "Cherry"};
System.out.println("Array: [Apple, Banana, Cherry]");
System.out.println("Valid indices: 0, 1, 2");
System.out.println("Length: " + fruits.length);
// Access valid index
System.out.println("\n--- Valid Access ---");
try {
String fruit = fruits[1];
System.out.println("fruits[1] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
// Access invalid index (too high)
System.out.println("\n--- Invalid Access (index too high) ---");
try {
String fruit = fruits[5];
System.out.println("fruits[5] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index 5 out of bounds");
System.out.println("Message: " + e.getMessage());
}
// Access invalid index (negative)
System.out.println("\n--- Invalid Access (negative index) ---");
try {
String fruit = fruits[-1];
System.out.println("fruits[-1] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Negative index");
System.out.println("Message: " + e.getMessage());
}
// Safe access pattern
System.out.println("\n--- Safe Access Pattern ---");
int[] indicesToTry = {0, 2, 5, -1, 1};
for (int index : indicesToTry) {
try {
String fruit = fruits[index];
System.out.println("fruits[" + index + "] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("fruits[" + index + "] = Invalid index!");
}
}
// Alternative: Check before accessing
System.out.println("\n--- Check Before Access ---");
int requestedIndex = -1;
if (requestedIndex >= 0 && requestedIndex < fruits.length) {
System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]);
} else {
System.out.println("Index " + requestedIndex + " is out of bounds (0-" + (fruits.length - 1) + ")");
}
System.out.println("\n=== Key Points ===");
System.out.println("""
1. Arrays have fixed size (0 to length-1)
2. Invalid index throws ArrayIndexOutOfBoundsException
3. Both too high AND negative indices are invalid
4. Can catch and handle, or check bounds first
5. getMessage() shows the invalid index number
""");
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
// Array Index Out of Bounds Exception
public class ArrayBounds {
public static void main(String[] args) {
System.out.println("=== Array Bounds Exception ===\n");
// Create an array
String[] fruits = {"Apple", "Banana", "Cherry"};
System.out.println("Array: [Apple, Banana, Cherry]");
System.out.println("Valid indices: 0, 1, 2");
System.out.println("Length: " + fruits.length);
// Access valid index
System.out.println("\n--- Valid Access ---");
try {
String fruit = fruits[1];
System.out.println("fruits[1] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
// Access invalid index (too high)
System.out.println("\n--- Invalid Access (index too high) ---");
try {
String fruit = fruits[5];
System.out.println("fruits[5] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Index 5 out of bounds");
System.out.println("Message: " + e.getMessage());
}
// Access invalid index (negative)
System.out.println("\n--- Invalid Access (negative index) ---");
try {
String fruit = fruits[-1];
System.out.println("fruits[-1] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Negative index");
System.out.println("Message: " + e.getMessage());
}
// Safe access pattern
System.out.println("\n--- Safe Access Pattern ---");
int[] indicesToTry = {0, 2, 5, -1, 1};
for (int index : indicesToTry) {
try {
String fruit = fruits[index];
System.out.println("fruits[" + index + "] = " + fruit);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("fruits[" + index + "] = Invalid index!");
}
}
// Alternative: Check before accessing
System.out.println("\n--- Check Before Access ---");
int requestedIndex = 1;
if (requestedIndex >= 0 && requestedIndex < fruits.length) {
System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]);
} else {
System.out.println("Index " + requestedIndex + " is out of bounds (0-" + (fruits.length - 1) + ")");
}
System.out.println("\n=== Key Points ===");
System.out.println("""
1. Arrays have fixed size (0 to length-1)
2. Invalid index throws ArrayIndexOutOfBoundsException
3. Both too high AND negative indices are invalid
4. Can catch and handle, or check bounds first
5. getMessage() shows the invalid index number
""");
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
public static void main(String[] args)
3public class ArrayBounds {4 public static void main(String[] args) {5 System.out.println("=== Array Bounds Exception ===\n");67 // Create an array //?create_array8 String[] fruits = {"Apple", "Banana", "Cherry"}; //?fruits_array9 System.out.println("Array: [Apple, Banana, Cherry]");10 System.out.println("Valid indices: 0, 1, 2");11 System.out.println("Length: " + fruits.length3);1213 // Access valid index //?valid_access14 System.out.println("\n--- Valid Access ---");15 try { //?try_validoutput=== Array Bounds Exception === Array: [Apple, Banana, Cherry] Valid indices: 0, 1, 2 Length: 3 --- Valid Access ---fruit ← Banana
14System.out.println("\n--- Valid Access ---");15try { //?try_valid16 String fruit→ Banana = fruits[1]Banana; //?access_valid17 System.out.println("fruits[1] = " + fruitBanana); //?print_valid18} catch (ArrayIndexOutOfBoundsException e) { //?catch_validoutputfruits[1] = BananaSystem.out.println(" --- Invalid Access (index too high) ---");
22// Access invalid index (too high) //?invalid_high23System.out.println("\n--- Invalid Access (index too high) ---");24try { //?try_highoutput --- Invalid Access (index too high) ---catch (ArrayIndexOutOfBoundsException e)
26 System.out.println("fruits[5] = " + fruit); //?print_high27} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) { //?catch_high28 System.out.println("Error: Index 5 out of bounds"); //?error_high29 System.out.println("Message: " + e.getMessage()); //?message_high30}outputError: Index 5 out of bounds Message: Index 5 out of bounds for length 3System.out.println(" --- Invalid Access (negative index) ---");
32// Access invalid index (negative) //?invalid_negative33System.out.println("\n--- Invalid Access (negative index) ---");34try { //?try_negativeoutput --- Invalid Access (negative index) ---catch (ArrayIndexOutOfBoundsException e)
36 System.out.println("fruits[-1] = " + fruit); //?print_negative37} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) { //?catch_negative38 System.out.println("Error: Negative index"); //?error_negative39 System.out.println("Message: " + e.getMessage()); //?message_negative40}outputError: Negative index Message: Index -1 out of bounds for length 3int[] indicesToTry = {0, 2, 5, -1, 1}; //?indices_to_try
42// Safe access pattern //?safe_pattern43System.out.println("\n--- Safe Access Pattern ---");44int[] indicesToTry = {0, 2, 5, -1, 1}; //?indices_to_tryoutput --- Safe Access Pattern ---for (int index : indicesToTry)
pass 1 of 546for (int index0 : indicesToTry) { //?loop_indices47 try { //?try_safeAll 5 passes — pass 1 is the card above pass indexe1 0 — 2 2 — 3 5 java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 4 -1 java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3 5 1 — fruit ← Apple
pass 1 of 546for (int index : indicesToTry) { //?loop_indices47 try { //?try_safe48 String fruit→ Apple = fruits[index]Apple; //?access_safe49 System.out.println("fruits[" + index0 + "] = " + fruitApple); //?print_safe50 } catch (ArrayIndexOutOfBoundsException e) { //?catch_safeoutputfruits[0] = AppleAll 5 passes — pass 1 is the card above pass fruits[index]indexefruit1 Apple 0 — Apple 2 Cherry 2 — Cherry 3 — 5 java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 — 4 — -1 java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3 — 5 Banana 1 — Banana catch (ArrayIndexOutOfBoundsException e)
pass 1 of 249 System.out.println("fruits[" + index + "] = " + fruit); //?print_safe50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) { //?catch_safe51 System.out.println("fruits[" + index5 + "] = Invalid index!"); //?error_safe52}outputfruits[5] = Invalid index!catch (ArrayIndexOutOfBoundsException e)
pass 2 of 249 System.out.println("fruits[" + index + "] = " + fruit); //?print_safe50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) { //?catch_safe51 System.out.println("fruits[" + index-1 + "] = Invalid index!"); //?error_safe52}outputfruits[-1] = Invalid index!requestedIndex ← 10
55// Alternative: Check before accessing //?check_first56System.out.println("\n--- Check Before Access ---");57int requestedIndex→ 10 = 10; //?requested_index58//@requestedIndex=10, 1, -1output --- Check Before Access ---else
61 System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]); //?safe_access62} else { //?else_invalid63 System.out.println("Index " + requestedIndex10 + " is out of bounds (0-" + (fruits.length3 - 1) + ")"); //?print_invalid64}outputIndex 10 is out of bounds (0-2)System.out.println(" === Key Points ===");
66 System.out.println("\n=== Key Points ===");67 System.out.println("""68 1. Arrays have fixed size (0 to length-1)69 2. Invalid index throws ArrayIndexOutOfBoundsException70 3. Both too high AND negative indices are invalid71 4. Can catch and handle, or check bounds first72 5. getMessage() shows the invalid index number73 """);74}output === Key Points === 1. Arrays have fixed size (0 to length-1) 2. Invalid index throws ArrayIndexOutOfBoundsException 3. Both too high AND negative indices are invalid 4. Can catch and handle, or check bounds first 5. getMessage() shows the invalid index number
public static void main(String[] args)
3public class ArrayBounds {4 public static void main(String[] args) {5 System.out.println("=== Array Bounds Exception ===\n");67 // Create an array8 String[] fruits = {"Apple", "Banana", "Cherry"};9 System.out.println("Array: [Apple, Banana, Cherry]");10 System.out.println("Valid indices: 0, 1, 2");11 System.out.println("Length: " + fruits.length3);1213 // Access valid index14 System.out.println("\n--- Valid Access ---");15 try {output=== Array Bounds Exception === Array: [Apple, Banana, Cherry] Valid indices: 0, 1, 2 Length: 3 --- Valid Access ---fruit ← Banana
14System.out.println("\n--- Valid Access ---");15try {16 String fruit→ Banana = fruits[1]Banana;17 System.out.println("fruits[1] = " + fruitBanana);18} catch (ArrayIndexOutOfBoundsException e) {outputfruits[1] = BananaSystem.out.println(" --- Invalid Access (index too high) ---");
22// Access invalid index (too high)23System.out.println("\n--- Invalid Access (index too high) ---");24try {output --- Invalid Access (index too high) ---catch (ArrayIndexOutOfBoundsException e)
26 System.out.println("fruits[5] = " + fruit);27} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) {28 System.out.println("Error: Index 5 out of bounds");29 System.out.println("Message: " + e.getMessage());30}outputError: Index 5 out of bounds Message: Index 5 out of bounds for length 3System.out.println(" --- Invalid Access (negative index) ---");
32// Access invalid index (negative)33System.out.println("\n--- Invalid Access (negative index) ---");34try {output --- Invalid Access (negative index) ---catch (ArrayIndexOutOfBoundsException e)
36 System.out.println("fruits[-1] = " + fruit);37} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) {38 System.out.println("Error: Negative index");39 System.out.println("Message: " + e.getMessage());40}outputError: Negative index Message: Index -1 out of bounds for length 3int[] indicesToTry = {0, 2, 5, -1, 1};
42// Safe access pattern43System.out.println("\n--- Safe Access Pattern ---");44int[] indicesToTry = {0, 2, 5, -1, 1};output --- Safe Access Pattern ---for (int index : indicesToTry)
pass 1 of 546for (int index0 : indicesToTry) {47 try {All 5 passes — pass 1 is the card above pass indexe1 0 — 2 2 — 3 5 java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 4 -1 java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3 5 1 — fruit ← Apple
pass 1 of 546for (int index : indicesToTry) {47 try {48 String fruit→ Apple = fruits[index]Apple;49 System.out.println("fruits[" + index0 + "] = " + fruitApple);50 } catch (ArrayIndexOutOfBoundsException e) {outputfruits[0] = AppleAll 5 passes — pass 1 is the card above pass fruits[index]indexefruit1 Apple 0 — Apple 2 Cherry 2 — Cherry 3 — 5 java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 — 4 — -1 java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3 — 5 Banana 1 — Banana catch (ArrayIndexOutOfBoundsException e)
pass 1 of 249 System.out.println("fruits[" + index + "] = " + fruit);50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) {51 System.out.println("fruits[" + index5 + "] = Invalid index!");52}outputfruits[5] = Invalid index!catch (ArrayIndexOutOfBoundsException e)
pass 2 of 249 System.out.println("fruits[" + index + "] = " + fruit);50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) {51 System.out.println("fruits[" + index-1 + "] = Invalid index!");52}outputfruits[-1] = Invalid index!requestedIndex ← -1
55// Alternative: Check before accessing56System.out.println("\n--- Check Before Access ---");57int requestedIndex→ -1 = -1;output --- Check Before Access ---else
60 System.out.println("fruits[" + requestedIndex + "] = " + fruits[requestedIndex]);61} else {62 System.out.println("Index " + requestedIndex-1 + " is out of bounds (0-" + (fruits.length3 - 1) + ")");63}outputIndex -1 is out of bounds (0-2)System.out.println(" === Key Points ===");
65 System.out.println("\n=== Key Points ===");66 System.out.println("""67 1. Arrays have fixed size (0 to length-1)68 2. Invalid index throws ArrayIndexOutOfBoundsException69 3. Both too high AND negative indices are invalid70 4. Can catch and handle, or check bounds first71 5. getMessage() shows the invalid index number72 """);73}output === Key Points === 1. Arrays have fixed size (0 to length-1) 2. Invalid index throws ArrayIndexOutOfBoundsException 3. Both too high AND negative indices are invalid 4. Can catch and handle, or check bounds first 5. getMessage() shows the invalid index number
public static void main(String[] args)
3public class ArrayBounds {4 public static void main(String[] args) {5 System.out.println("=== Array Bounds Exception ===\n");67 // Create an array8 String[] fruits = {"Apple", "Banana", "Cherry"};9 System.out.println("Array: [Apple, Banana, Cherry]");10 System.out.println("Valid indices: 0, 1, 2");11 System.out.println("Length: " + fruits.length3);1213 // Access valid index14 System.out.println("\n--- Valid Access ---");15 try {output=== Array Bounds Exception === Array: [Apple, Banana, Cherry] Valid indices: 0, 1, 2 Length: 3 --- Valid Access ---fruit ← Banana
14System.out.println("\n--- Valid Access ---");15try {16 String fruit→ Banana = fruits[1]Banana;17 System.out.println("fruits[1] = " + fruitBanana);18} catch (ArrayIndexOutOfBoundsException e) {outputfruits[1] = BananaSystem.out.println(" --- Invalid Access (index too high) ---");
22// Access invalid index (too high)23System.out.println("\n--- Invalid Access (index too high) ---");24try {output --- Invalid Access (index too high) ---catch (ArrayIndexOutOfBoundsException e)
26 System.out.println("fruits[5] = " + fruit);27} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) {28 System.out.println("Error: Index 5 out of bounds");29 System.out.println("Message: " + e.getMessage());30}outputError: Index 5 out of bounds Message: Index 5 out of bounds for length 3System.out.println(" --- Invalid Access (negative index) ---");
32// Access invalid index (negative)33System.out.println("\n--- Invalid Access (negative index) ---");34try {output --- Invalid Access (negative index) ---catch (ArrayIndexOutOfBoundsException e)
36 System.out.println("fruits[-1] = " + fruit);37} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) {38 System.out.println("Error: Negative index");39 System.out.println("Message: " + e.getMessage());40}outputError: Negative index Message: Index -1 out of bounds for length 3int[] indicesToTry = {0, 2, 5, -1, 1};
42// Safe access pattern43System.out.println("\n--- Safe Access Pattern ---");44int[] indicesToTry = {0, 2, 5, -1, 1};output --- Safe Access Pattern ---for (int index : indicesToTry)
pass 1 of 546for (int index0 : indicesToTry) {47 try {All 5 passes — pass 1 is the card above pass indexe1 0 — 2 2 — 3 5 java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 4 -1 java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3 5 1 — fruit ← Apple
pass 1 of 546for (int index : indicesToTry) {47 try {48 String fruit→ Apple = fruits[index]Apple;49 System.out.println("fruits[" + index0 + "] = " + fruitApple);50 } catch (ArrayIndexOutOfBoundsException e) {outputfruits[0] = AppleAll 5 passes — pass 1 is the card above pass fruits[index]indexefruit1 Apple 0 — Apple 2 Cherry 2 — Cherry 3 — 5 java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3 — 4 — -1 java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3 — 5 Banana 1 — Banana catch (ArrayIndexOutOfBoundsException e)
pass 1 of 249 System.out.println("fruits[" + index + "] = " + fruit);50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3) {51 System.out.println("fruits[" + index5 + "] = Invalid index!");52}outputfruits[5] = Invalid index!catch (ArrayIndexOutOfBoundsException e)
pass 2 of 249 System.out.println("fruits[" + index + "] = " + fruit);50} catch (ArrayIndexOutOfBoundsException ejava.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3) {51 System.out.println("fruits[" + index-1 + "] = Invalid index!");52}outputfruits[-1] = Invalid index!requestedIndex ← 1
55// Alternative: Check before accessing56System.out.println("\n--- Check Before Access ---");57int requestedIndex→ 1 = 1;output --- Check Before Access ---if (requestedIndex >= 0 && requestedIndex < fruits.length)
59if (requestedIndex1 >= 0 && requestedIndex < fruits.length3) {60 System.out.println("fruits[" + requestedIndex1 + "] = " + fruits[requestedIndex]Banana);61} else {outputfruits[1] = BananaSystem.out.println(" === Key Points ===");
65 System.out.println("\n=== Key Points ===");66 System.out.println("""67 1. Arrays have fixed size (0 to length-1)68 2. Invalid index throws ArrayIndexOutOfBoundsException69 3. Both too high AND negative indices are invalid70 4. Can catch and handle, or check bounds first71 5. getMessage() shows the invalid index number72 """);73}output === Key Points === 1. Arrays have fixed size (0 to length-1) 2. Invalid index throws ArrayIndexOutOfBoundsException 3. Both too high AND negative indices are invalid 4. Can catch and handle, or check bounds first 5. getMessage() shows the invalid index number
ArrayIndexOutOfBoundsException when accessing index outside array range.
Multiple catch blocks
Handle different exceptions differently.
// Multiple Catch Blocks
public class MultipleCatch {
public static void main(String[] args) {
System.out.println("=== Multiple Catch Blocks ===\n");
// Different exceptions need different handling
String[] data = {"10", "abc", "20", null, "30"};
int[] divisors = {2, 5, 0, 4, 1};
System.out.println("Processing data with multiple exception types...\n");
for (int i = 0; i < data.length; i++) {
System.out.println("--- Processing index " + i + " ---");
try {
// Step 1: Parse string to int (may throw NumberFormatException)
String str = data[i];
System.out.println("String value: " + str);
int number = Integer.parseInt(str);
System.out.println("Parsed number: " + number);
// Step 2: Divide (may throw ArithmeticException)
int divisor = divisors[i];
int result = number / divisor;
System.out.println("Result: " + number + " / " + divisor + " = " + result);
} catch (NumberFormatException e) {
System.out.println("ERROR: Cannot parse '" + data[i] + "' as number");
System.out.println(" Type: NumberFormatException");
} catch (ArithmeticException e) {
System.out.println("ERROR: Division by zero");
System.out.println(" Type: ArithmeticException");
} catch (NullPointerException e) {
System.out.println("ERROR: Null value encountered");
System.out.println(" Type: NullPointerException");
}
System.out.println();
}
// Multi-catch syntax (Java 7+)
System.out.println("=== Multi-Catch Syntax ===\n");
String[] testValues = {"100", "bad", null};
int testDivisor = 10;
for (String val : testValues) {
try {
int num = Integer.parseInt(val);
int result = num / testDivisor;
System.out.println(val + " / " + testDivisor + " = " + result);
} catch (NumberFormatException | NullPointerException e) {
// Handle both the same way
System.out.println("Invalid input: " + val);
System.out.println(" Exception: " + e.getClass().getSimpleName());
}
}
// Order matters - specific before general
System.out.println("\n=== Catch Order (Specific First) ===\n");
demonstrateCatchOrder();
System.out.println("=== Key Points ===");
System.out.println("""
1. Multiple catch blocks handle different exceptions
2. Order: specific exceptions before general ones
3. Multi-catch: catch (TypeA | TypeB e) for same handling
4. Only ONE catch block executes per exception
5. Put most specific exception types first
""");
}
static void demonstrateCatchOrder() {
String value = "not a number";
try {
int num = Integer.parseInt(value);
System.out.println("Parsed: " + num);
} catch (NumberFormatException e) {
// Specific exception - caught first
System.out.println("Caught NumberFormatException (specific)");
} catch (IllegalArgumentException e) {
// Parent of NumberFormatException - never reached for NFE
System.out.println("Caught IllegalArgumentException (parent)");
} catch (Exception e) {
// Most general - catches anything else
System.out.println("Caught Exception (general)");
}
System.out.println("\nNote: NumberFormatException extends IllegalArgumentException");
System.out.println("So the specific catch must come first!");
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
public static void main(String[] args)
3public class MultipleCatch {4 public static void main(String[] args) {5 System.out.println("=== Multiple Catch Blocks ===\n");67 // Different exceptions need different handling //?different_exceptions8 String[] data = {"10", "abc", "20", null, "30"}; //?data_array9 int[] divisors = {2, 5, 0, 4, 1}; //?divisors_array1011 System.out.println("Processing data with multiple exception types...\n");output=== Multiple Catch Blocks === Processing data with multiple exception types...for (int i = 0; i < data.length; i++)
pass 1 of 513for (int i0 = 0; i < data.length5; i++) { //?main_loop14 System.out.println("--- Processing index " + i0 + " ---");output--- Processing index 0 ---All 5 passes — pass 1 is the card above pass iedata[i]1 0 — — 2 1 java.lang.NumberFormatException: For input string: "abc" abc 3 2 java.lang.ArithmeticException: / by zero — 4 3 java.lang.NumberFormatException: Cannot parse null string null 5 4 — — str ← 10, number ← 10, divisor ← 2, result ← 5
pass 1 of 516try { //?try_block17 // Step 1: Parse string to int (may throw NumberFormatException) //?step118 String str→ 10 = data[i]10; //?get_string19 System.out.println("String value: " + str10);20 int number→ 10 = Integer.parseInt(str10); //?parse_int21 System.out.println("Parsed number: " + number10);2223 // Step 2: Divide (may throw ArithmeticException) //?step224 int divisor→ 2 = divisors[i]2; //?get_divisor25 int result→ 5 = number10 / divisor2; //?divide26 System.out.println("Result: " + number10 + " / " + divisor2 + " = " + result5);outputString value: 10 Parsed number: 10 Result: 10 / 2 = 5All 5 passes — pass 1 is the card above pass data[i]idivisors[i]estrnumberdivisorresult1 10 0 2 — 10 10 2 5 2 abc 1 — java.lang.NumberFormatException: For input string: "abc" abc — — — 3 20 2 0 java.lang.ArithmeticException: / by zero 20 20 0 — 4 null 3 — java.lang.NumberFormatException: Cannot parse null string null — — — 5 30 4 1 — 30 30 1 30 System.out.println();
41 System.out.println();42}catch (NumberFormatException e)
pass 1 of 228} catch (NumberFormatException ejava.lang.NumberFormatException: For input string: "abc") { //?catch_number_format29 System.out.println("ERROR: Cannot parse '" + data[i]abc + "' as number");30 System.out.println(" Type: NumberFormatException");outputERROR: Cannot parse 'abc' as number Type: NumberFormatExceptionvalues this step1iSystem.out.println();
41 System.out.println();42}catch (ArithmeticException e)
32} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_arithmetic33 System.out.println("ERROR: Division by zero");34 System.out.println(" Type: ArithmeticException");outputERROR: Division by zero Type: ArithmeticExceptionSystem.out.println();
41 System.out.println();42}catch (NumberFormatException e)
pass 2 of 228} catch (NumberFormatException ejava.lang.NumberFormatException: Cannot parse null string) { //?catch_number_format29 System.out.println("ERROR: Cannot parse '" + data[i]null + "' as number");30 System.out.println(" Type: NumberFormatException");outputERROR: Cannot parse 'null' as number Type: NumberFormatExceptionvalues this step3iSystem.out.println();
41 System.out.println();42}System.out.println();
41 System.out.println();42}testDivisor ← 10
44// Multi-catch syntax (Java 7+) //?multi_catch45System.out.println("=== Multi-Catch Syntax ===\n");4647String[] testValues = {"100", "bad", null}; //?test_values48int testDivisor→ 10 = 10; //?test_divisoroutput=== Multi-Catch Syntax ===for (String val : testValues)
pass 1 of 350for (String val100 : testValues) { //?multi_loop51 try { //?try_multiAll 3 passes — pass 1 is the card above pass vale1 100 — 2 bad java.lang.NumberFormatException: For input string: "bad" 3 null java.lang.NumberFormatException: Cannot parse null string num ← 100, result ← 10
pass 1 of 350for (String val : testValues) { //?multi_loop51 try { //?try_multi52 int num→ 100 = Integer.parseInt(val100); //?parse_multi53 int result→ 10 = num100 / testDivisor10; //?divide_multi54 System.out.println(val100 + " / " + testDivisor10 + " = " + result10);output100 / 10 = 10All 3 passes — pass 1 is the card above pass valtestDivisorenumresult1 100 10 — 100 10 2 bad — java.lang.NumberFormatException: For input string: "bad" — — 3 null — java.lang.NumberFormatException: Cannot parse null string — — catch (NumberFormatException | NullPointerException e)
pass 1 of 256} catch (NumberFormatException | NullPointerException ejava.lang.NumberFormatException: For input string: "bad") { //?multi_catch_block57 // Handle both the same way58 System.out.println("Invalid input: " + valbad);59 System.out.println(" Exception: " + e.getClass().getSimpleName());60}outputInvalid input: bad Exception: NumberFormatExceptioncatch (NumberFormatException | NullPointerException e)
pass 2 of 256} catch (NumberFormatException | NullPointerException ejava.lang.NumberFormatException: Cannot parse null string) { //?multi_catch_block57 // Handle both the same way58 System.out.println("Invalid input: " + valnull);59 System.out.println(" Exception: " + e.getClass().getSimpleName());60}outputInvalid input: null Exception: NumberFormatExceptionSystem.out.println(" === Catch Order (Specific First) === ");
63// Order matters - specific before general //?order_matters64System.out.println("\n=== Catch Order (Specific First) ===\n");6566demonstrateCatchOrder(); //?call_demooutput === Catch Order (Specific First) ===value ← not a number
78static void demonstrateCatchOrder() { //?demo_method79 String value→ not a number = "not a number"; //?demo_valuetry
81try { //?try_order82 int num = Integer.parseInt(valuenot a number); //?parse_order83 System.out.println("Parsed: " + num);catch (NumberFormatException e)
85} catch (NumberFormatException ejava.lang.NumberFormatException: For input string: "not a number") { //?catch_specific86 // Specific exception - caught first87 System.out.println("Caught NumberFormatException (specific)");outputCaught NumberFormatException (specific)System.out.println(" Note: NumberFormatException extends IllegalArgume…
66 demonstrateCatchOrder(); //?call_demo6768 System.out.println("=== Key Points ===");69 System.out.println("""70 1. Multiple catch blocks handle different exceptions71 2. Order: specific exceptions before general ones72 3. Multi-catch: catch (TypeA | TypeB e) for same handling73 4. Only ONE catch block executes per exception74 5. Put most specific exception types first75 """);76}7778static void demonstrateCatchOrder() { //?demo_method79 String value = "not a number"; //?demo_value8081 try { //?try_order82 int num = Integer.parseInt(value); //?parse_order83 System.out.println("Parsed: " + num);8485 } catch (NumberFormatException e) { //?catch_specific86 // Specific exception - caught first87 System.out.println("Caught NumberFormatException (specific)");8889 } catch (IllegalArgumentException e) { //?catch_parent90 // Parent of NumberFormatException - never reached for NFE91 System.out.println("Caught IllegalArgumentException (parent)");9293 } catch (Exception e) { //?catch_general94 // Most general - catches anything else95 System.out.println("Caught Exception (general)");96 }9798 System.out.println("\nNote: NumberFormatException extends IllegalArgumentException");99 System.out.println("So the specific catch must come first!");100}output Note: NumberFormatException extends IllegalArgumentException So the specific catch must come first! === Key Points === 1. Multiple catch blocks handle different exceptions 2. Order: specific exceptions before general ones 3. Multi-catch: catch (TypeA | TypeB e) for same handling 4. Only ONE catch block executes per exception 5. Put most specific exception types first
Specific exceptions first, general exception last. Order matters.
Exception hierarchy
Catch parent type to handle all subtypes.
// Exception Hierarchy
public class ExceptionHierarchy {
public static void main(String[] args) {
System.out.println("=== Exception Hierarchy ===\n");
// Exception inheritance tree
System.out.println("Java Exception Hierarchy:");
System.out.println("""
Throwable
├── Error (serious, don't catch)
│ ├── OutOfMemoryError
│ └── StackOverflowError
└── Exception (catch these)
├── RuntimeException (unchecked)
│ ├── NullPointerException
│ ├── ArithmeticException
│ ├── IndexOutOfBoundsException
│ │ └── ArrayIndexOutOfBoundsException
│ ├── IllegalArgumentException
│ │ └── NumberFormatException
│ └── ClassCastException
└── IOException (checked)
└── FileNotFoundException
""");
// Catching parent catches all children
System.out.println("--- Parent Exception Catches Children ---\n");
Object[] testCases = {
"divide_zero", // ArithmeticException
"null_pointer", // NullPointerException
"bad_index", // ArrayIndexOutOfBoundsException
"bad_parse" // NumberFormatException
};
for (Object testCase : testCases) {
System.out.println("Test: " + testCase);
try {
triggerException((String)testCase);
} catch (RuntimeException e) {
// RuntimeException catches ALL runtime exceptions
System.out.println(" Caught: " + e.getClass().getSimpleName());
System.out.println(" Message: " + e.getMessage());
}
System.out.println();
}
// Catching Exception catches everything
System.out.println("--- Catching Exception (Most General) ---\n");
try {
triggerException("null_pointer");
} catch (Exception e) {
System.out.println("Exception catches any exception type");
System.out.println("Actual type: " + e.getClass().getName());
}
// instanceof check for specific handling
System.out.println("\n--- instanceof for Specific Handling ---\n");
for (Object testCase : testCases) {
try {
triggerException((String)testCase);
} catch (Exception e) {
handleWithInstanceof(e);
}
}
// Why use specific exceptions?
System.out.println("\n=== Why Catch Specific Exceptions? ===");
System.out.println("""
1. Different errors need different recovery
2. Don't hide unexpected errors
3. Better error messages for users
4. Easier debugging
5. Code is self-documenting
""");
}
static void triggerException(String type) {
switch (type) {
case "divide_zero" -> {
int result = 10 / 0;
}
case "null_pointer" -> {
String s = null;
s.length();
}
case "bad_index" -> {
int[] arr = {1, 2, 3};
int val = arr[10];
}
case "bad_parse" -> {
int num = Integer.parseInt("abc");
}
}
}
static void handleWithInstanceof(Exception e) {
System.out.print("Handling: ");
if (e instanceof ArithmeticException) {
System.out.println("Math error - check your calculations");
} else if (e instanceof NullPointerException) {
System.out.println("Null error - check for null values");
} else if (e instanceof ArrayIndexOutOfBoundsException) {
System.out.println("Index error - check array bounds");
} else if (e instanceof NumberFormatException) {
System.out.println("Parse error - check input format");
} else {
System.out.println("Unknown error: " + e.getClass().getSimpleName());
}
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
public static void main(String[] args)
3public class ExceptionHierarchy {4 public static void main(String[] args) {5 System.out.println("=== Exception Hierarchy ===\n");67 // Exception inheritance tree //?inheritance_tree8 System.out.println("Java Exception Hierarchy:");9 System.out.println("""10 Throwable11 ├── Error (serious, don't catch)12 │ ├── OutOfMemoryError13 │ └── StackOverflowError14 └── Exception (catch these)15 ├── RuntimeException (unchecked)16 │ ├── NullPointerException17 │ ├── ArithmeticException18 │ ├── IndexOutOfBoundsException19 │ │ └── ArrayIndexOutOfBoundsException20 │ ├── IllegalArgumentException21 │ │ └── NumberFormatException22 │ └── ClassCastException23 └── IOException (checked)24 └── FileNotFoundException25 """);2627 // Catching parent catches all children //?parent_catches_children28 System.out.println("--- Parent Exception Catches Children ---\n");2930 Object[] testCases = { //?test_cases31 "divide_zero", // ArithmeticException32 "null_pointer", // NullPointerException33 "bad_index", // ArrayIndexOutOfBoundsException34 "bad_parse" // NumberFormatException35 };output=== Exception Hierarchy === Java Exception Hierarchy: Throwable ├── Error (serious, don't catch) │ ├── OutOfMemoryError │ └── StackOverflowError └── Exception (catch these) ├── RuntimeException (unchecked) │ ├── NullPointerException │ ├── ArithmeticException │ ├── IndexOutOfBoundsException │ │ └── ArrayIndexOutOfBoundsException │ ├── IllegalArgumentException │ │ └── NumberFormatException │ └── ClassCastException └── IOException (checked) └── FileNotFoundException --- Parent Exception Catches Children ---for (Object testCase : testCases)
pass 1 of 437for (Object testCasedivide_zero : testCases) { //?loop_tests38 System.out.println("Test: " + testCasedivide_zero);outputTest: divide_zeroAll 4 passes — pass 1 is the card above pass testCase1 divide_zero 2 null_pointer 3 bad_index 4 bad_parse static void triggerException(String type)
pass 1 of 982static void triggerException(String typedivide_zero) { //?trigger_method83 switch (type) { //?switch_typeAll 9 passes — pass 1 is the card above pass typee1 divide_zero — 2 null_pointer — 3 bad_index — 4 bad_parse — 5 null_pointer java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null 6 divide_zero java.lang.ArithmeticException: / by zero 7 null_pointer java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null 8 bad_index java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3 9 bad_parse java.lang.NumberFormatException: For input string: "abc" catch (RuntimeException e)
pass 1 of 441 triggerException((String)testCase); //?trigger_exception42} catch (RuntimeException ejava.lang.ArithmeticException: / by zero) { //?catch_runtime43 // RuntimeException catches ALL runtime exceptions44 System.out.println(" Caught: " + e.getClass().getSimpleName());45 System.out.println(" Message: " + e.getMessage());46}output Caught: ArithmeticException Message: / by zeroAll 4 passes — pass 1 is the card above pass e1 java.lang.ArithmeticException: / by zero 2 java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null 3 java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3 4 java.lang.NumberFormatException: For input string: "abc" System.out.println();
46 }47 System.out.println();48}System.out.println();
46 }47 System.out.println();48}System.out.println();
46 }47 System.out.println();48}System.out.println();
46 }47 System.out.println();48}4950// Catching Exception catches everything //?catch_all51System.out.println("--- Catching Exception (Most General) ---\n");output--- Catching Exception (Most General) ---catch (Exception e)
54 triggerException("null_pointer"); //?trigger_null55} catch (Exception ejava.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null) { //?catch_exception56 System.out.println("Exception catches any exception type");57 System.out.println("Actual type: " + e.getClass().getName());58}outputException catches any exception type Actual type: java.lang.NullPointerExceptionSystem.out.println(" --- instanceof for Specific Handling --- ");
60// instanceof check for specific handling //?instanceof_check61System.out.println("\n--- instanceof for Specific Handling ---\n");output --- instanceof for Specific Handling ---for (Object testCase : testCases)
pass 1 of 463for (Object testCasedivide_zero : testCases) { //?loop_instanceof64 try { //?try_instanceofAll 4 passes — pass 1 is the card above pass testCasee1 divide_zero java.lang.ArithmeticException: / by zero 2 null_pointer java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null 3 bad_index java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3 4 bad_parse java.lang.NumberFormatException: For input string: "abc" try
pass 1 of 463for (Object testCase : testCases) { //?loop_instanceof64 try { //?try_instanceof65 triggerException((String)testCase); //?trigger_instanceof66 } catch (Exception e) { //?catch_instanceofAll 4 passes — pass 1 is the card above pass e1 java.lang.ArithmeticException: / by zero 2 java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null 3 java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3 4 java.lang.NumberFormatException: For input string: "abc" catch (Exception e)
pass 1 of 465 triggerException((String)testCase); //?trigger_instanceof66} catch (Exception ejava.lang.ArithmeticException: / by zero) { //?catch_instanceof67 handleWithInstanceof(ejava.lang.ArithmeticException: / by zero); //?handle_instanceof68}All 4 passes — pass 1 is the card above pass e1 java.lang.ArithmeticException: / by zero 2 java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null 3 java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3 4 java.lang.NumberFormatException: For input string: "abc" static void handleWithInstanceof(Exception e)
pass 1 of 4101static void handleWithInstanceof(Exception ejava.lang.ArithmeticException: / by zero) { //?handle_method102 System.out.print("Handling: ");outputHandling:All 4 passes — pass 1 is the card above pass e1 java.lang.ArithmeticException: / by zero 2 java.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null 3 java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3 4 java.lang.NumberFormatException: For input string: "abc" if (e instanceof ArithmeticException)
66 } catch (Exception e) { //?catch_instanceof67 handleWithInstanceof(ejava.lang.ArithmeticException: / by zero); //?handle_instanceof68 }69 }7071 // Why use specific exceptions? //?why_specific72 System.out.println("\n=== Why Catch Specific Exceptions? ===");73 System.out.println("""74 1. Different errors need different recovery75 2. Don't hide unexpected errors76 3. Better error messages for users77 4. Easier debugging78 5. Code is self-documenting79 """);80}8182static void triggerException(String type) { //?trigger_method83 switch (type) { //?switch_type84 case "divide_zero" -> { //?case_divide85 int result = 10 / 0;86 }87 case "null_pointer" -> { //?case_null88 String s = null;89 s.length();90 }91 case "bad_index" -> { //?case_index92 int[] arr = {1, 2, 3};93 int val = arr[10];94 }95 case "bad_parse" -> { //?case_parse96 int num = Integer.parseInt("abc");97 }98 }99}100101static void handleWithInstanceof(Exception e) { //?handle_method102 System.out.print("Handling: ");103104 if (e instanceof ArithmeticException) { //?check_arithmetic105 System.out.println("Math error - check your calculations");106 } else if (e instanceof NullPointerException) { //?check_nulloutputMath error - check your calculationsif (e instanceof NullPointerException)
66 } catch (Exception e) { //?catch_instanceof67 handleWithInstanceof(ejava.lang.NullPointerException: Cannot invoke "String.length()" because "<local3>" is null); //?handle_instanceof68 }69 }7071 // Why use specific exceptions? //?why_specific72 System.out.println("\n=== Why Catch Specific Exceptions? ===");73 System.out.println("""74 1. Different errors need different recovery75 2. Don't hide unexpected errors76 3. Better error messages for users77 4. Easier debugging78 5. Code is self-documenting79 """);80}8182static void triggerException(String type) { //?trigger_method83 switch (type) { //?switch_type84 case "divide_zero" -> { //?case_divide85 int result = 10 / 0;86 }87 case "null_pointer" -> { //?case_null88 String s = null;89 s.length();90 }91 case "bad_index" -> { //?case_index92 int[] arr = {1, 2, 3};93 int val = arr[10];94 }95 case "bad_parse" -> { //?case_parse96 int num = Integer.parseInt("abc");97 }98 }99}100101static void handleWithInstanceof(Exception e) { //?handle_method102 System.out.print("Handling: ");103104 if (e instanceof ArithmeticException) { //?check_arithmetic105 System.out.println("Math error - check your calculations");106 } else if (e instanceof NullPointerException) { //?check_null107 System.out.println("Null error - check for null values");108 } else if (e instanceof ArrayIndexOutOfBoundsException) { //?check_arrayoutputNull error - check for null valuesif (e instanceof ArrayIndexOutOfBoundsException)
66 } catch (Exception e) { //?catch_instanceof67 handleWithInstanceof(ejava.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 3); //?handle_instanceof68 }69 }7071 // Why use specific exceptions? //?why_specific72 System.out.println("\n=== Why Catch Specific Exceptions? ===");73 System.out.println("""74 1. Different errors need different recovery75 2. Don't hide unexpected errors76 3. Better error messages for users77 4. Easier debugging78 5. Code is self-documenting79 """);80}8182static void triggerException(String type) { //?trigger_method83 switch (type) { //?switch_type84 case "divide_zero" -> { //?case_divide85 int result = 10 / 0;86 }87 case "null_pointer" -> { //?case_null88 String s = null;89 s.length();90 }91 case "bad_index" -> { //?case_index92 int[] arr = {1, 2, 3};93 int val = arr[10];94 }95 case "bad_parse" -> { //?case_parse96 int num = Integer.parseInt("abc");97 }98 }99}100101static void handleWithInstanceof(Exception e) { //?handle_method102 System.out.print("Handling: ");103104 if (e instanceof ArithmeticException) { //?check_arithmetic105 System.out.println("Math error - check your calculations");106 } else if (e instanceof NullPointerException) { //?check_null107 System.out.println("Null error - check for null values");108 } else if (e instanceof ArrayIndexOutOfBoundsException) { //?check_array109 System.out.println("Index error - check array bounds");110 } else if (e instanceof NumberFormatException) { //?check_numberoutputIndex error - check array boundsif (e instanceof NumberFormatException)
66 } catch (Exception e) { //?catch_instanceof67 handleWithInstanceof(ejava.lang.NumberFormatException: For input string: "abc"); //?handle_instanceof68 }69 }7071 // Why use specific exceptions? //?why_specific72 System.out.println("\n=== Why Catch Specific Exceptions? ===");73 System.out.println("""74 1. Different errors need different recovery75 2. Don't hide unexpected errors76 3. Better error messages for users77 4. Easier debugging78 5. Code is self-documenting79 """);80}8182static void triggerException(String type) { //?trigger_method83 switch (type) { //?switch_type84 case "divide_zero" -> { //?case_divide85 int result = 10 / 0;86 }87 case "null_pointer" -> { //?case_null88 String s = null;89 s.length();90 }91 case "bad_index" -> { //?case_index92 int[] arr = {1, 2, 3};93 int val = arr[10];94 }95 case "bad_parse" -> { //?case_parse96 int num = Integer.parseInt("abc");97 }98 }99}100101static void handleWithInstanceof(Exception e) { //?handle_method102 System.out.print("Handling: ");103104 if (e instanceof ArithmeticException) { //?check_arithmetic105 System.out.println("Math error - check your calculations");106 } else if (e instanceof NullPointerException) { //?check_null107 System.out.println("Null error - check for null values");108 } else if (e instanceof ArrayIndexOutOfBoundsException) { //?check_array109 System.out.println("Index error - check array bounds");110 } else if (e instanceof NumberFormatException) { //?check_number111 System.out.println("Parse error - check input format");112 } else { //?check_otheroutputParse error - check input format === Why Catch Specific Exceptions? === 1. Different errors need different recovery 2. Don't hide unexpected errors 3. Better error messages for users 4. Easier debugging 5. Code is self-documenting
Catching Exception catches everything. Be specific when possible.
Finally block
Code that always runs, even after exception.
// Finally Block
public class FinallyBlock {
public static void main(String[] args) {
System.out.println("=== Finally Block ===\n");
// Finally always executes
System.out.println("--- Finally with Exception ---");
try {
System.out.println("1. In try block");
int result = 10 / 0;
System.out.println("2. This won't print");
} catch (ArithmeticException e) {
System.out.println("3. In catch block");
} finally {
System.out.println("4. In finally block (ALWAYS runs)");
}
System.out.println("5. After try-catch-finally");
// Finally without exception
System.out.println("\n--- Finally without Exception ---");
try {
System.out.println("1. In try block");
int result = 10 / 2;
System.out.println("2. Result: " + result);
} catch (ArithmeticException e) {
System.out.println("3. In catch block (SKIPPED)");
} finally {
System.out.println("4. In finally block (ALWAYS runs)");
}
System.out.println("5. After try-catch-finally");
// Finally for cleanup
System.out.println("\n--- Finally for Cleanup ---");
demonstrateCleanup(true);
System.out.println();
demonstrateCleanup(false);
// Finally with return
System.out.println("\n--- Finally with Return ---");
int result1 = calculateWithReturn(10, 2);
System.out.println("Result: " + result1);
int result2 = calculateWithReturn(10, 0);
System.out.println("Result: " + result2);
// Try-finally without catch
System.out.println("\n--- Try-Finally (no catch) ---");
try {
System.out.println("Performing operation...");
// Operations here
} finally {
System.out.println("Cleanup runs even without catch block");
}
System.out.println("\n=== Key Points ===");
System.out.println("""
1. finally ALWAYS executes
2. Executes after try OR after catch
3. Use for cleanup: close files, release resources
4. finally runs even if return in try/catch
5. Can have try-finally without catch
""");
}
static void demonstrateCleanup(boolean success) {
System.out.println("Starting operation (success=" + success + ")");
// Simulating resource acquisition
System.out.println(" [RESOURCE] Acquired");
try {
if (success) {
System.out.println(" [OPERATION] Success");
} else {
System.out.println(" [OPERATION] About to fail...");
throw new RuntimeException("Operation failed");
}
} catch (RuntimeException e) {
System.out.println(" [ERROR] " + e.getMessage());
} finally {
// Always release the resource
System.out.println(" [RESOURCE] Released (finally)");
}
}
static int calculateWithReturn(int a, int b) {
try {
int result = a / b;
System.out.println(" Calculation successful");
return result;
} catch (ArithmeticException e) {
System.out.println(" Calculation failed");
return -1;
} finally {
// This runs BEFORE the return!
System.out.println(" Finally block executed");
}
}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
public static void main(String[] args)
3public class FinallyBlock {4 public static void main(String[] args) {5 System.out.println("=== Finally Block ===\n");67 // Finally always executes //?finally_always8 System.out.println("--- Finally with Exception ---");output=== Finally Block === --- Finally with Exception ---try
10try { //?try_exception11 System.out.println("1. In try block");12 int result = 10 / 0; //?cause_exception13 System.out.println("2. This won't print");output1. In try blockcatch (ArithmeticException e)
13 System.out.println("2. This won't print");14} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_exception15 System.out.println("3. In catch block");16} finally { //?finally_exceptionoutput3. In catch block15 System.out.println("3. In catch block");16} finally { //?finally_exception17 System.out.println("4. In finally block (ALWAYS runs)");18}output4. In finally block (ALWAYS runs)System.out.println("5. After try-catch-finally");
20System.out.println("5. After try-catch-finally");2122// Finally without exception //?finally_no_exception23System.out.println("\n--- Finally without Exception ---");output5. After try-catch-finally --- Finally without Exception ---result ← 5
25try { //?try_no_exception26 System.out.println("1. In try block");27 int result→ 5 = 10 / 2; //?no_exception28 System.out.println("2. Result: " + result5);29} catch (ArithmeticException e) { //?catch_no_exceptionoutput1. In try block 2. Result: 530 System.out.println("3. In catch block (SKIPPED)");31} finally { //?finally_no_exception_block32 System.out.println("4. In finally block (ALWAYS runs)");33}output4. In finally block (ALWAYS runs)System.out.println("5. After try-catch-finally");
35System.out.println("5. After try-catch-finally");3637// Finally for cleanup //?finally_cleanup38System.out.println("\n--- Finally for Cleanup ---");3940demonstrateCleanup(true); //?demo_success41System.out.println();output5. After try-catch-finally --- Finally for Cleanup ---static void demonstrateCleanup(boolean success)
pass 1 of 273static void demonstrateCleanup(boolean successtrue) { //?cleanup_method74 System.out.println("Starting operation (success=" + successtrue + ")");7576 // Simulating resource acquisition //?simulate_resource77 System.out.println(" [RESOURCE] Acquired");outputStarting operation (success=true) [RESOURCE] Acquiredif (success)
79try { //?try_cleanup80 if (successtrue) { //?check_success81 System.out.println(" [OPERATION] Success");82 } else { //?operation_failoutput [OPERATION] Successpass 1 of 2 40 demonstrateCleanup(true); //?demo_success41 System.out.println();42 demonstrateCleanup(false); //?demo_failure4344 // Finally with return //?finally_return45 System.out.println("\n--- Finally with Return ---");4647 int result1 = calculateWithReturn(10, 2); //?call_return_success48 System.out.println("Result: " + result1);4950 int result2 = calculateWithReturn(10, 0); //?call_return_error51 System.out.println("Result: " + result2);5253 // Try-finally without catch //?try_finally_only54 System.out.println("\n--- Try-Finally (no catch) ---");5556 try { //?try_only57 System.out.println("Performing operation...");58 // Operations here59 } finally { //?finally_only60 System.out.println("Cleanup runs even without catch block");61 }6263 System.out.println("\n=== Key Points ===");64 System.out.println("""65 1. finally ALWAYS executes66 2. Executes after try OR after catch67 3. Use for cleanup: close files, release resources68 4. finally runs even if return in try/catch69 5. Can have try-finally without catch70 """);71}7273static void demonstrateCleanup(boolean success) { //?cleanup_method74 System.out.println("Starting operation (success=" + success + ")");7576 // Simulating resource acquisition //?simulate_resource77 System.out.println(" [RESOURCE] Acquired");7879 try { //?try_cleanup80 if (success) { //?check_success81 System.out.println(" [OPERATION] Success");82 } else { //?operation_fail83 System.out.println(" [OPERATION] About to fail...");84 throw new RuntimeException("Operation failed"); //?throw_exception85 }86 } catch (RuntimeException e) { //?catch_cleanup87 System.out.println(" [ERROR] " + e.getMessage());88 } finally { //?finally_cleanup_block89 // Always release the resource90 System.out.println(" [RESOURCE] Released (finally)"); //?release_resource91 }output [RESOURCE] Released (finally)static void demonstrateCleanup(boolean success)
pass 2 of 273static void demonstrateCleanup(boolean successfalse) { //?cleanup_method74 System.out.println("Starting operation (success=" + successfalse + ")");7576 // Simulating resource acquisition //?simulate_resource77 System.out.println(" [RESOURCE] Acquired");outputStarting operation (success=false) [RESOURCE] Acquiredelse
81 System.out.println(" [OPERATION] Success");82} else { //?operation_fail83 System.out.println(" [OPERATION] About to fail...");84 throw new RuntimeException("Operation failed"); //?throw_exception85}output [OPERATION] About to fail...catch (RuntimeException e)
85 }86} catch (RuntimeException ejava.lang.RuntimeException: Operation failed) { //?catch_cleanup87 System.out.println(" [ERROR] " + e.getMessage());88} finally { //?finally_cleanup_blockoutput [ERROR] Operation failedpass 2 of 2 41 System.out.println();42 demonstrateCleanup(false); //?demo_failure4344 // Finally with return //?finally_return45 System.out.println("\n--- Finally with Return ---");4647 int result1 = calculateWithReturn(10, 2); //?call_return_success48 System.out.println("Result: " + result1);4950 int result2 = calculateWithReturn(10, 0); //?call_return_error51 System.out.println("Result: " + result2);5253 // Try-finally without catch //?try_finally_only54 System.out.println("\n--- Try-Finally (no catch) ---");5556 try { //?try_only57 System.out.println("Performing operation...");58 // Operations here59 } finally { //?finally_only60 System.out.println("Cleanup runs even without catch block");61 }6263 System.out.println("\n=== Key Points ===");64 System.out.println("""65 1. finally ALWAYS executes66 2. Executes after try OR after catch67 3. Use for cleanup: close files, release resources68 4. finally runs even if return in try/catch69 5. Can have try-finally without catch70 """);71}7273static void demonstrateCleanup(boolean success) { //?cleanup_method74 System.out.println("Starting operation (success=" + success + ")");7576 // Simulating resource acquisition //?simulate_resource77 System.out.println(" [RESOURCE] Acquired");7879 try { //?try_cleanup80 if (success) { //?check_success81 System.out.println(" [OPERATION] Success");82 } else { //?operation_fail83 System.out.println(" [OPERATION] About to fail...");84 throw new RuntimeException("Operation failed"); //?throw_exception85 }86 } catch (RuntimeException e) { //?catch_cleanup87 System.out.println(" [ERROR] " + e.getMessage());88 } finally { //?finally_cleanup_block89 // Always release the resource90 System.out.println(" [RESOURCE] Released (finally)"); //?release_resource91 }output [RESOURCE] Released (finally) --- Finally with Return ---static int calculateWithReturn(int a, int b)
pass 1 of 294static int calculateWithReturn(int a10, int b2) { //?return_method95 try { //?try_returnresult ← 5
pass 1 of 294static int calculateWithReturn(int a, int b) { //?return_method95 try { //?try_return96 int result→ 5 = a10 / b2; //?calc_return97 System.out.println(" Calculation successful");98 return result5; //?return_success99 } catch (ArithmeticException e) { //?catch_returnoutput Calculation successfulresult1 ← 5
pass 1 of 247 int result1→ 5 = calculateWithReturn(10, 2); //?call_return_success48 System.out.println("Result: " + result15);4950 int result2 = calculateWithReturn(10, 0); //?call_return_error51 System.out.println("Result: " + result2);5253 // Try-finally without catch //?try_finally_only54 System.out.println("\n--- Try-Finally (no catch) ---");5556 try { //?try_only57 System.out.println("Performing operation...");58 // Operations here59 } finally { //?finally_only60 System.out.println("Cleanup runs even without catch block");61 }6263 System.out.println("\n=== Key Points ===");64 System.out.println("""65 1. finally ALWAYS executes66 2. Executes after try OR after catch67 3. Use for cleanup: close files, release resources68 4. finally runs even if return in try/catch69 5. Can have try-finally without catch70 """);71}7273static void demonstrateCleanup(boolean success) { //?cleanup_method74 System.out.println("Starting operation (success=" + success + ")");7576 // Simulating resource acquisition //?simulate_resource77 System.out.println(" [RESOURCE] Acquired");7879 try { //?try_cleanup80 if (success) { //?check_success81 System.out.println(" [OPERATION] Success");82 } else { //?operation_fail83 System.out.println(" [OPERATION] About to fail...");84 throw new RuntimeException("Operation failed"); //?throw_exception85 }86 } catch (RuntimeException e) { //?catch_cleanup87 System.out.println(" [ERROR] " + e.getMessage());88 } finally { //?finally_cleanup_block89 // Always release the resource90 System.out.println(" [RESOURCE] Released (finally)"); //?release_resource91 }92}9394static int calculateWithReturn(int a, int b) { //?return_method95 try { //?try_return96 int result = a / b; //?calc_return97 System.out.println(" Calculation successful");98 return result; //?return_success99 } catch (ArithmeticException e) { //?catch_return100 System.out.println(" Calculation failed");101 return -1; //?return_error102 } finally { //?finally_return_block103 // This runs BEFORE the return!104 System.out.println(" Finally block executed"); //?finally_before_return105 }output Finally block executed Result: 5static int calculateWithReturn(int a, int b)
pass 2 of 294static int calculateWithReturn(int a10, int b0) { //?return_method95 try { //?try_returntry
pass 2 of 294static int calculateWithReturn(int a, int b) { //?return_method95 try { //?try_return96 int result = a10 / b0; //?calc_return97 System.out.println(" Calculation successful");catch (ArithmeticException e)
98 return result; //?return_success99} catch (ArithmeticException ejava.lang.ArithmeticException: / by zero) { //?catch_return100 System.out.println(" Calculation failed");101 return -1; //?return_error102} finally { //?finally_return_blockoutput Calculation failedresult2 ← -1
pass 2 of 250 int result2→ -1 = calculateWithReturn(10, 0); //?call_return_error51 System.out.println("Result: " + result2-1);5253 // Try-finally without catch //?try_finally_only54 System.out.println("\n--- Try-Finally (no catch) ---");5556 try { //?try_only57 System.out.println("Performing operation...");58 // Operations here59 } finally { //?finally_only60 System.out.println("Cleanup runs even without catch block");61 }6263 System.out.println("\n=== Key Points ===");64 System.out.println("""65 1. finally ALWAYS executes66 2. Executes after try OR after catch67 3. Use for cleanup: close files, release resources68 4. finally runs even if return in try/catch69 5. Can have try-finally without catch70 """);71}7273static void demonstrateCleanup(boolean success) { //?cleanup_method74 System.out.println("Starting operation (success=" + success + ")");7576 // Simulating resource acquisition //?simulate_resource77 System.out.println(" [RESOURCE] Acquired");7879 try { //?try_cleanup80 if (success) { //?check_success81 System.out.println(" [OPERATION] Success");82 } else { //?operation_fail83 System.out.println(" [OPERATION] About to fail...");84 throw new RuntimeException("Operation failed"); //?throw_exception85 }86 } catch (RuntimeException e) { //?catch_cleanup87 System.out.println(" [ERROR] " + e.getMessage());88 } finally { //?finally_cleanup_block89 // Always release the resource90 System.out.println(" [RESOURCE] Released (finally)"); //?release_resource91 }92}9394static int calculateWithReturn(int a, int b) { //?return_method95 try { //?try_return96 int result = a / b; //?calc_return97 System.out.println(" Calculation successful");98 return result; //?return_success99 } catch (ArithmeticException e) { //?catch_return100 System.out.println(" Calculation failed");101 return -1; //?return_error102 } finally { //?finally_return_block103 // This runs BEFORE the return!104 System.out.println(" Finally block executed"); //?finally_before_return105 }output Finally block executed Result: -1 --- Try-Finally (no catch) ---try
56try { //?try_only57 System.out.println("Performing operation...");58 // Operations hereoutputPerforming operation...58 // Operations here59} finally { //?finally_only60 System.out.println("Cleanup runs even without catch block");61}outputCleanup runs even without catch blockSystem.out.println(" === Key Points ===");
63 System.out.println("\n=== Key Points ===");64 System.out.println("""65 1. finally ALWAYS executes66 2. Executes after try OR after catch67 3. Use for cleanup: close files, release resources68 4. finally runs even if return in try/catch69 5. Can have try-finally without catch70 """);71}output === Key Points === 1. finally ALWAYS executes 2. Executes after try OR after catch 3. Use for cleanup: close files, release resources 4. finally runs even if return in try/catch 5. Can have try-finally without catch
finally { cleanup } runs whether exception occurred or not.
Exercise: Practical.java
Build a robust file reader with complete exception handling