CSC409 Advanced Java Programming

Advanced Java ProgrammingUnit 49 min read

Java Packages, Exception Handling & Error Management

Unit 4 of Advanced Java Programming covers Java’s package system (imports, access modifiers, and package hierarchies) alongside exception handling (checked vs. unchecked, custom exceptions, and the `try-catch-finally` mechanism). It explains how to structure code modularly, handle runtime errors gracefully, and use Jav

Core Concepts

1. Java Packages: Organization and Access Control

Definition and Purpose

  • A package is a namespace that groups related classes/interfaces to avoid naming conflicts and control access.
  • Why use packages?
    • Modularity: Logical grouping (e.g., java.util, javax.swing).
    • Access control: public, protected, default, and private modifiers restrict visibility.
    • Versioning: Packages allow library updates without breaking existing code.

Package Declaration and Structure

  • Declare at the top of a file:
    package com.example.utils; // Standard convention: reverse domain + module
    
  • Directory structure must match the package name:
    src/
    └── com/
        └── example/
            └── utils/
                └── MathOperations.java
    
  • Import statements:
    import java.util.*; // Wildcard import (use sparingly)
    import com.example.utils.MathOperations; // Specific import
    

Access Modifiers and Package Visibility

Modifier Within Class Within Package Subclass (any package) Anywhere
public ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ❌
default ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌

Creating and Using Custom Packages

Example: Create a package geometry with a Circle class.

// File: src/geometry/Circle.java
package geometry;
public class Circle {
    public double radius;
    public Circle(double r) { radius = r; }
    public double area() { return Math.PI * radius * radius; }
}

Usage:

import geometry.Circle;
public class Main {
    public static void main(String[] args) {
        Circle c = new Circle(5.0);
        System.out.println("Area: " + c.area());
    }
}

Static Imports

  • Import static members directly (avoids prefixing with class name):
    import static java.lang.Math.PI;
    import static java.lang.System.out;
    
    Example:
    out.println("Value of PI: " + PI);
    

2. Exception Handling: Errors vs. Exceptions

Definitions

  • Error: Severe system-level issues (e.g., OutOfMemoryError, StackOverflowError). Cannot be caught or recovered.
  • Exception: Runtime or checked issues (e.g., NullPointerException, FileNotFoundException). Can be handled.

Exception Hierarchy

classDiagram
    class Throwable {
        <<abstract>>
        +String getMessage()
    }
    class Error {
        <<extends Throwable>>
        +OutOfMemoryError
        +StackOverflowError
    }
    class Exception {
        <<extends Throwable>>
        +RuntimeException
        +IOException
    }
    class RuntimeException {
        <<extends Exception>>
        +NullPointerException
        +ArrayIndexOutOfBoundsException
    }
    class IOException {
        <<extends Exception>>
        +FileNotFoundException
    }
    Throwable <|-- Error
    Throwable <|-- Exception
    Exception <|-- RuntimeException
    Exception <|-- IOException

Checked vs. Unchecked Exceptions

Feature Checked Exception Unchecked Exception (RuntimeException)
Inheritance Extends Exception Extends RuntimeException
Compilation Must be declared or handled No compilation requirement
Examples IOException, SQLException NullPointerException, ArrayIndexOutOfBoundsException
Recovery Expected to be handled Often programming errors

Handling Exceptions: try-catch-finally

try {
    // Code that may throw an exception
    FileReader file = new FileReader("nonexistent.txt");
} catch (FileNotFoundException e) {
    // Handle the exception
    System.err.println("File not found: " + e.getMessage());
} finally {
    // Always executes (cleanup)
    System.out.println("Execution complete.");
}

Custom Exceptions

Example: Create InvalidAgeException for age validation.

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

// Usage
public class AgeValidator {
    public static void validate(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18+");
        }
    }
}

3. Keywords: throws vs. throw

Keyword Usage Example
throw Explicitly throws an exception throw new ArithmeticException("Divide by zero");
throws Declares exceptions in method signature public void readFile() throws IOException { ... }

When to Use finally?

  • Critical for resource cleanup (e.g., closing files, database connections).
  • Example:
    FileInputStream file = null;
    try {
        file = new FileInputStream("data.txt");
        // Read data
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (file != null) {
            file.close(); // Ensures resource is released
        }
    }
    

4. Best Practices and Common Pitfalls

Do’s and Don’ts

  • Do:
    • Catch specific exceptions (avoid catching Exception generically).
    • Use finally for cleanup (e.g., closing streams).
    • Document exceptions with @throws in Javadoc.
  • Don’t:
    • Swallow exceptions silently (catch (Exception e) {}).
    • Use exceptions for flow control (e.g., throw new Exception("Invalid input");).
    • Ignore finally blocks in critical sections.

Common Exception Scenarios

Scenario Exception Type Solution
File not found FileNotFoundException Check file path; handle gracefully.
Invalid user input NumberFormatException Validate input before parsing.
Database connection failure SQLException Implement retry logic or fallback.
Null reference access NullPointerException Initialize objects properly.

Exam Tip

High-Weightage Topics

  1. Package Structure:

    • Explain the difference between path (where JVM looks for .class files) and classpath (list of directories/JARs for loading classes).
    • Example Question: "How would you compile and run a program with classes in com.example package?" Answer:
      javac -d . com/example/Main.java  # Compiles to ./com/example/Main.class
      java com.example.Main             # Runs with classpath set
      
  2. Exception Handling:

    • Differentiate throws (declaration) and throw (execution).
    • Example Question: "When is the finally block skipped?" Answer: Only if the JVM exits abruptly (e.g., System.exit() or fatal error).
  3. Custom Exceptions:

    • Write a program to validate user input (e.g., email format) using custom exceptions.
    • Example:
      class InvalidEmailException extends Exception {}
      public void validateEmail(String email) throws InvalidEmailException {
          if (!email.contains("@")) throw new InvalidEmailException("Invalid email");
      }
      
  4. Access Modifiers in Packages:

    • Example Question: "Can a protected method in Package A be accessed by a class in Package B?" Answer: Only if the class in Package B is a subclass of the class in Package A.

Common Mistakes to Avoid

  • Forgetting to declare exceptions in method signatures (e.g., throws IOException).
  • Catching Exception or Throwable too broadly (use specific exceptions).
  • Not closing resources in finally (use try-with-resources in Java 7+):
    try (FileInputStream file = new FileInputStream("data.txt")) {
        // Auto-closes file
    } catch (IOException e) {
        e.printStackTrace();
    }
    

Past Exam Patterns

  • Short Answer (2-4 marks):
    • Define throws vs. throw.
    • List 3 checked exceptions.
    • Explain the purpose of finally.
  • Programming (6-10 marks):
    • Write a program to handle ArithmeticException for division by zero.
    • Create a custom exception for invalid login attempts.
    • Demonstrate package usage with a MathUtils class in com.math package.
  • Theory (5-8 marks):
    • Compare path and classpath.
    • Explain the hierarchy of Throwable with examples.
    • Describe how to structure a large project using packages.

Java exception hierarchyHierarchy of `Throwable`, `Error`, `Exception`, and subclasses (Image: Arunreginald, CC BY-SA 3.0, via Wikimedia Commons)

mindmap
  root((Exception Handling))
    Checked
      IOException
      SQLException
    Unchecked
      RuntimeException
      NullPointerException
      ArrayIndexOutOfBoundsException
    Custom
      InvalidAgeException
      InvalidInputException
    Keywords
      throw
      throws
      try-catch-finally
    Best Practices
      Specific catches
      Resource cleanup
      Documentation

Based on the TU BSc CSIT syllabus for Advanced Java Programming (CSC409), unit 4.

Discussion

Loading…