Try-Catch in Java
Learn how to handle errors gracefully in your programs
💡 Think of try-catch like wearing a safety net when doing gymnastics - if you fall (error happens), the net catches you instead of getting hurt! The 'try' block is where you attempt something risky, and the 'catch' block saves you if something goes wrong.
🛡️ What is Try-Catch?
Try-catch is a mechanism to handle errors (exceptions) in Java. You 'try' to run some code that might fail, and if it does fail, you 'catch' the error and handle it gracefully instead of crashing your program.
public class BasicTryCatch { public static void main(String[] args) { System.out.println("Program started"); try { // This is risky code - might cause an error! int result = 10 / 0; // Division by zero! System.out.println("Result: " + result); } catch (ArithmeticException e) { // If an error happens, we catch it here System.out.println("Oops! Can't divide by zero!"); System.out.println("Error message: " + e.getMessage()); } // Program continues running - no crash! System.out.println("Program continues running..."); System.out.println("Program ended successfully"); }}// Output:// Program started// Oops! Can't divide by zero!// Error message: / by zero// Program continues running...// Program ended successfully🔍 🔄 How It Works
The try-catch mechanism follows these steps:
Try Block
Code that might throw an exception is placed here
Exception Occurs
If an error happens, execution jumps to catch block
Catch Block
Handles the exception and prevents program crash
Continue Execution
Program continues normally after handling the exception
public class TryCatchFlow { public static void main(String[] args) { System.out.println("1. Before try block"); try { System.out.println("2. Inside try - start"); int[] numbers = {1, 2, 3}; System.out.println("3. Accessing array..."); // This will cause an error! System.out.println(numbers[10]); // Index out of bounds! // This line never executes! System.out.println("4. This won't print!"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("5. Caught in catch block!"); System.out.println(" Error: " + e.getMessage()); } System.out.println("6. After try-catch - program continues"); }}// Output:// 1. Before try block// 2. Inside try - start// 3. Accessing array...// 5. Caught in catch block!// Error: Index 10 out of bounds for length 3// 6. After try-catch - program continues🎯 Multiple Catch Blocks
public class MultipleCatch { public static void main(String[] args) { // Example 1: Different types of errors handleDifferentErrors("123"); handleDifferentErrors("abc"); handleDifferentErrors(null); System.out.println("\n--- All errors handled gracefully! ---"); } public static void handleDifferentErrors(String input) { System.out.println("\nProcessing: " + input); try { // Multiple things could go wrong here! int length = input.length(); // NullPointerException? int number = Integer.parseInt(input); // NumberFormatException? int result = 100 / number; // ArithmeticException? System.out.println("Success! Result: " + result); } catch (NullPointerException e) { System.out.println("Error: Input is null!"); } catch (NumberFormatException e) { System.out.println("Error: '" + input + "' is not a number!"); } catch (ArithmeticException e) { System.out.println("Error: Cannot divide by zero!"); } catch (Exception e) { // Generic catch for any other exception System.out.println("Error: Something unexpected happened!"); } }}// Output:// Processing: 123// Success! Result: 0//// Processing: abc// Error: 'abc' is not a number!//// Processing: null// Error: Input is null!//// --- All errors handled gracefully! ---📊 Real-World Example: Safe Array Access
public class SafeArrayAccess { public static void main(String[] args) { String[] students = {"Alice", "Bob", "Charlie", "David"}; // Try to access different indices accessStudent(students, 0); // Valid accessStudent(students, 2); // Valid accessStudent(students, 10); // Invalid - out of bounds! accessStudent(students, -1); // Invalid - negative index! System.out.println("\nProgram completed without crashing!"); } public static void accessStudent(String[] array, int index) { try { System.out.println("\nAccessing index " + index + "..."); String student = array[index]; System.out.println("Student found: " + student); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error: Index " + index + " doesn't exist!"); System.out.println("Valid indices are 0 to " + (array.length - 1)); } }}// Output:// Accessing index 0...// Student found: Alice//// Accessing index 2...// Student found: Charlie//// Accessing index 10...// Error: Index 10 doesn't exist!// Valid indices are 0 to 3//// Accessing index -1...// Error: Index -1 doesn't exist!// Valid indices are 0 to 3//// Program completed without crashing!🔢 Real-World Example: Safe Number Parsing
import java.util.Scanner;public class SafeNumberParser { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("=== Age Calculator ==="); System.out.print("Enter your age: "); String input = scanner.nextLine(); try { // Try to convert string to number int age = Integer.parseInt(input); // Validate the age if (age < 0) { System.out.println("Age cannot be negative!"); } else if (age > 150) { System.out.println("That's too old to be true!"); } else { int birthYear = 2024 - age; System.out.println("You are " + age + " years old"); System.out.println("You were born around " + birthYear); } } catch (NumberFormatException e) { System.out.println("Error: '" + input + "' is not a valid number!"); System.out.println("Please enter a numeric value like 25"); } scanner.close(); }}// Example runs://// Enter your age: 25// You are 25 years old// You were born around 1999//// Enter your age: abc// Error: 'abc' is not a valid number!// Please enter a numeric value like 25📁 Real-World Example: File Operations
import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class SafeFileReader { public static void main(String[] args) { readFile("data.txt"); readFile("missing.txt"); } public static void readFile(String filename) { System.out.println("\n--- Reading file: " + filename + " ---"); try { File file = new File(filename); Scanner scanner = new Scanner(file); System.out.println("File opened successfully!"); int lineNumber = 1; while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println("Line " + lineNumber + ": " + line); lineNumber++; } scanner.close(); System.out.println("File read complete!"); } catch (FileNotFoundException e) { System.out.println("Error: File '" + filename + "' not found!"); System.out.println("Please check if the file exists."); } catch (Exception e) { System.out.println("Error reading file: " + e.getMessage()); } }}// Output (when data.txt exists but missing.txt doesn't)://// --- Reading file: data.txt ---// File opened successfully!// Line 1: Hello World// Line 2: This is a test file// File read complete!//// --- Reading file: missing.txt ---// Error: File 'missing.txt' not found!// Please check if the file exists.➗ Real-World Example: Division Calculator
public class DivisionCalculator { public static void main(String[] args) { System.out.println("=== Division Calculator ===\n"); // Test various division scenarios divide(10, 2); divide(15, 3); divide(7, 0); // Division by zero! divide(100, 4); System.out.println("\nCalculator finished safely!"); } public static void divide(int numerator, int denominator) { try { System.out.println("Calculating: " + numerator + " ÷ " + denominator); int result = numerator / denominator; int remainder = numerator % denominator; System.out.println("Result: " + result); System.out.println("Remainder: " + remainder); System.out.println(); } catch (ArithmeticException e) { System.out.println("ERROR: Cannot divide by zero!"); System.out.println("Please use a non-zero denominator."); System.out.println(); } }}// Output:// === Division Calculator ===//// Calculating: 10 ÷ 2// Result: 5// Remainder: 0//// Calculating: 15 ÷ 3// Result: 5// Remainder: 0//// Calculating: 7 ÷ 0// ERROR: Cannot divide by zero!// Please use a non-zero denominator.//// Calculating: 100 ÷ 4// Result: 25// Remainder: 0//// Calculator finished safely!🔑 Key Concepts
Try Block
Contains code that might throw an exception
try { risky code here }
Catch Block
Handles specific types of exceptions
catch (ExceptionType e) { handle error }
Multiple Catch
You can catch different exception types separately
Multiple catch blocks for different error types
Exception Object
Contains information about what went wrong
e.getMessage() tells you the error message
✨ Best Practices
- ✓Catch specific exceptions before general ones (most specific first)
- ✓Don't catch exceptions you can't handle meaningfully
- ✓Always log or display meaningful error messages
- ✓Never leave catch blocks empty - at least log the error
- ✓Use try-catch for exceptional situations, not normal control flow
- ✓Consider using try-with-resources for resource management
💼 Interview Tips
- •Understand the difference between checked and unchecked exceptions
- •Know that catch blocks are evaluated in order (top to bottom)
- •Remember that only one catch block executes per exception
- •Understand exception propagation up the call stack
- •Know when to catch vs when to propagate (throw) exceptions
- •Be familiar with common exception types (NullPointerException, IOException, etc.)