Basic Try-Catch/Try-Except Structure

Java: java try { int result = 10 / 0; // ArithmeticException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); System.out.println(e.getMessage()); } finally { System.out.println("Cleanup code"); }

TrackJava to Python Journey
Current SectionPython Basics
Progress13 of 19

1. Basic Try-Catch/Try-Except Structure

Java:

try {
    int result = 10 / 0;  // ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
    System.out.println(e.getMessage());
} finally {
    System.out.println("Cleanup code");
}

Python:

try:
    result = 10 / 0  # ZeroDivisionError
except ZeroDivisionError as e:
    print("Cannot divide by zero")
    print(str(e))
finally:
    print("Cleanup code")

Key Similarities:

  • Both use try-catch/except blocks.
  • Both support finally for cleanup.
  • Both capture exception details.

Key Differences:

  • Java uses catch; Python uses except.
  • Python uses as to bind exception to variable; Java uses constructor syntax.

2. Exception Types and Hierarchy

Java Exception Hierarchy:

Throwable
├── Exception
│   ├── IOException
│   ├── SQLException
│   ├── ArithmeticException
│   ├── NullPointerException
│   └── ...
└── Error
    ├── OutOfMemoryError
    └── ...

Python Exception Hierarchy:

BaseException
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
└── Exception
    ├── StopIteration
    ├── ArithmeticError
    │   ├── ZeroDivisionError
    │   └── FloatingPointError
    ├── LookupError
    │   ├── IndexError
    │   └── KeyError
    ├── NameError
    ├── TypeError
    ├── ValueError
    ├── IOError
    ├── RuntimeError
    └── ...

3. Catching Multiple Exceptions

Java:

try {
    String[] arr = {"a", "b"};
    int value = Integer.parseInt(arr[5]);  // Can throw multiple exceptions
} catch (NumberFormatException e) {
    System.out.println("Invalid number format: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index out of bounds");
} catch (Exception e) {  // Catch-all (catch parent class last)
    System.out.println("Generic exception: " + e.getMessage());
}

Python:

try:
    arr = ["a", "b"]
    value = int(arr[5])  # Can throw multiple exceptions
except ValueError as e:
    print(f"Invalid number format: {e}")
except IndexError as e:
    print("Array index out of bounds")
except Exception as e:  # Catch-all (catch parent class last)
    print(f"Generic exception: {e}")

Multi-Exception Tuple (Python 2.6+):

try:
    value = int(arr[5])
except (ValueError, IndexError) as e:
    print(f"Either ValueError or IndexError: {e}")
except Exception as e:
    print(f"Other exception: {e}")

Key Difference:

  • Both catch specific exceptions first, then generic ones.
  • Python allows catching multiple exceptions in one clause using tuple syntax.
  • Java requires separate catch blocks.

4. Else Clause (Python-Specific)

Python Only:

try:
    result = 10 / 2  # No exception
except ZeroDivisionError as e:
    print("Cannot divide by zero")
else:
    print(f"Division successful: {result}")  # Executes only if no exception
finally:
    print("Cleanup")

# Output:
# Division successful: 5.0
# Cleanup

Java Equivalent (using flag or structure):

boolean success = false;
try {
    int result = 10 / 2;
    success = true;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}
if (success) {
    System.out.println("Division successful");
}

5. Custom Exceptions

Java:

public class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class Person {
    private int age;
    
    public void setAge(int age) throws InvalidAgeException {
        if (age < 0 || age > 120) {
            throw new InvalidAgeException("Age must be between 0 and 120");
        }
        this.age = age;
    }
}

// Usage
try {
    Person person = new Person();
    person.setAge(150);
} catch (InvalidAgeException e) {
    System.out.println("Error: " + e.getMessage());
}

Python:

class InvalidAgeException(Exception):
    """Custom exception for invalid age"""
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

class Person:
    def __init__(self):
        self.age = 0
    
    def set_age(self, age):
        if age < 0 or age > 120:
            raise InvalidAgeException("Age must be between 0 and 120")
        self.age = age

# Usage
try:
    person = Person()
    person.set_age(150)
except InvalidAgeException as e:
    print(f"Error: {e}")

6. Checked vs Unchecked Exceptions

Java (Checked Exceptions):

import java.io.*;

// Method must declare checked exceptions using 'throws'
public void readFile(String filename) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    String line = reader.readLine();
    reader.close();
}

// Caller must handle or propagate
try {
    readFile("file.txt");
} catch (IOException e) {
    System.out.println("File not found");
}

Python (No Checked Exceptions):

# No requirement to declare exceptions
def read_file(filename):
    with open(filename, 'r') as f:
        line = f.readline()

# Caller can choose to handle or not
try:
    read_file("file.txt")
except FileNotFoundError:
    print("File not found")

# Or don't handle (exception propagates)
read_file("file.txt")  # May crash if file not found

Key Difference:

  • Java has checked exceptions: Compiler requires handling or declaration.
  • Python has no checked exceptions: Developers must handle exceptions at runtime if needed.

7. Finally vs Context Managers

Java Finally:

FileReader reader = null;
try {
    reader = new FileReader("file.txt");
    // Read file
} catch (IOException e) {
    System.out.println("Error reading file");
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Python with Finally:

reader = None
try:
    reader = open("file.txt", "r")
    # Read file
except IOError:
    print("Error reading file")
finally:
    if reader:
        reader.close()

Python with Context Manager (Preferred):

# Automatically handles cleanup (closes file)
try:
    with open("file.txt", "r") as reader:
        content = reader.read()
except IOError:
    print("Error reading file")

Key Difference:

  • Python's with statement (context managers) is cleaner for resource management.
  • Java relies on finally blocks and try-with-resources (Java 7+).

8. Try-With-Resources (Java 7+)

Java:

// Automatic resource management
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    String line = reader.readLine();
    System.out.println(line);
} catch (IOException e) {
    System.out.println("Error reading file");
}
// reader is automatically closed

Python Equivalent:

try:
    with open("file.txt", "r") as reader:
        line = reader.readline()
        print(line)
except IOError:
    print("Error reading file")
# File is automatically closed

9. Throwing Exceptions

Java:

public void validateEmail(String email) throws IllegalArgumentException {
    if (!email.contains("@")) {
        throw new IllegalArgumentException("Invalid email format");
    }
}

// Usage
try {
    validateEmail("invalid-email");
} catch (IllegalArgumentException e) {
    System.out.println("Validation failed: " + e.getMessage());
}

Python:

def validate_email(email):
    if "@" not in email:
        raise ValueError("Invalid email format")

# Usage
try:
    validate_email("invalid-email")
except ValueError as e:
    print(f"Validation failed: {e}")

10. Exception Chaining

Java:

try {
    // Some operation
    int result = 10 / 0;
} catch (ArithmeticException e) {
    // Wrap in custom exception with original cause
    throw new RuntimeException("Calculation failed", e);
}

// Catch and print stack trace
try {
    // ...
} catch (RuntimeException e) {
    e.printStackTrace();  // Shows cause as well
}

Python:

try:
    result = 10 / 0
except ZeroDivisionError as e:
    raise ValueError("Calculation failed") from e

# Catch and print
try:
    # ...
except ValueError as e:
    print(f"Error: {e}")
    print(f"Caused by: {e.__cause__}")

11. Practical Example: File Processing

Java:

public class FileProcessor {
    public void processFile(String filename) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filename));
            String line;
            int lineCount = 0;
            
            while ((line = reader.readLine()) != null) {
                if (line.trim().isEmpty()) {
                    throw new IllegalArgumentException("Empty line found");
                }
                lineCount++;
            }
            
            System.out.println("Processed " + lineCount + " lines");
            
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO Error: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            System.out.println("Validation Error: " + e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

// Usage
FileProcessor processor = new FileProcessor();
try {
    processor.processFile("data.txt");
} catch (IOException e) {
    e.printStackTrace();
}

Python:

class FileProcessor:
    def process_file(self, filename):
        try:
            with open(filename, "r") as reader:
                line_count = 0
                for line in reader:
                    if not line.strip():
                        raise ValueError("Empty line found")
                    line_count += 1
                
                print(f"Processed {line_count} lines")
        
        except FileNotFoundError:
            print(f"File not found: {filename}")
        except IOError as e:
            print(f"IO Error: {e}")
        except ValueError as e:
            print(f"Validation Error: {e}")

# Usage
processor = FileProcessor()
processor.process_file("data.txt")

12. Common Built-in Exceptions

  • Division by zero

    • Java: ArithmeticException
    • Python: ZeroDivisionError
    • When Raised: Divide by zero
  • Array/Index out of bounds

    • Java: ArrayIndexOutOfBoundsException
    • Python: IndexError
    • When Raised: Access invalid index
  • Dictionary key not found

    • Java: KeyNotFoundException (Map)
    • Python: KeyError
    • When Raised: Access missing dict key
  • Type mismatch

    • Java: ClassCastException
    • Python: TypeError
    • When Raised: Wrong type operation
  • Null/None reference

    • Java: NullPointerException
    • Python: AttributeError / TypeError
    • When Raised: Access on None
  • File not found

    • Java: FileNotFoundException
    • Python: FileNotFoundError
    • When Raised: Open missing file
  • Invalid value

    • Java: IllegalArgumentException
    • Python: ValueError
    • When Raised: Invalid argument
  • Name not found

    • Java: NoSuchFieldException
    • Python: NameError
    • When Raised: Undefined variable

Summary Table

  • Exception Keyword

    • Java: catch
    • Python: except
  • Multiple Exceptions

    • Java: Multiple catch blocks
    • Python: Single except tuple or multiple blocks
  • Finally

    • Java: finally block
    • Python: finally block
  • Cleanup

    • Java: finally or try-with-resources
    • Python: finally or with statement (context manager)
  • Custom Exceptions

    • Java: Extend Exception class
    • Python: Extend Exception class
  • Exception Declaration

    • Java: throws in method signature
    • Python: No declaration needed
  • Checked Exceptions

    • Java: Yes (enforced at compile time)
    • Python: No (runtime only)
  • Else Block

    • Java: Not available
    • Python: Available (else after except)
  • Re-raise

    • Java: throw e;
    • Python: raise
  • Exception Chaining

    • Java: throw new Exception(msg, cause)
    • Python: raise NewException() from e
  • Resource Management

    • Java: try-with-resources (Java 7+)
    • Python: with statement (context manager)