Organizing Packages & Handling Accidents (Packages & Exceptions)
Master code organization using packages, control privacy using access modifiers (public/private), and protect your apps from crashes using try-catch exception handling.
As your code grows, keeping it organized and crash-proof becomes vital! In this chapter, we explore how packages act as filing cabinets, how privacy settings (private/public) protect data, and how try-catch blocks catch unexpected errors before they crash your program.
5.1. 1. Packages & Privacy Settings (Access Modifiers)
Definition: Packages group related classes into folders; Access Modifiers govern which parts of your program can view or edit variables and methods.
Core Working Principles:
- Packages: Folders that prevent name collisions (e.g.,
package com.myapp.services;). - 4 Access Modifiers:
- •
private: Secret. Accessible ONLY inside the exact same class. - •
default(no modifier): Visible to classes inside the same package folder. - •
protected: Visible to same package + inherited child classes. - •
public: World visible. Accessible anywhere in the application.
• private: Your personal diary. Only YOU can read it!
• public: A billboard on the highway. Anyone driving past can read it!
5-Marks Exam Scoring Points
- Packages organize classes into folder namespaces.
- private restricts access to the enclosing class only (Encapsulation).
- public allows unrestricted access across the application.
5.2. 2. Handling Accidents: Exception Handling (try-catch-finally)
Definition: Exception handling catches unexpected runtime errors gracefully so your program keeps running instead of crashing.
Core Working Principles:
- What is an Exception? A runtime accident (e.g., dividing by zero, missing file, loss of network connection).
- The
try-catch-finallySafety Net: - •
try: Wrap risky code inside this block. - •
catch: Intercepts and handles errors if an accident happens. - •
finally: Code that ALWAYS runs unconditionally at the end (used for cleanup).
• try: Go outside and attempt your walk.
• catch: If it starts raining (Exception), open your umbrella so you don't get soaked!
• finally: Take off your shoes when you get home (runs whether it rained or was sunny).
try {
int result = 10 / 0; // Arithmetic Error: Cannot divide by zero!
} catch (ArithmeticException e) {
System.out.println("Accident caught! You cannot divide by zero.");
} finally {
System.out.println("Cleanup complete. Application still running smoothly!");
}
5-Marks Exam Scoring Points
- Exception handling prevents application crashes during unexpected errors.
- try monitors risky blocks; catch handles specific errors.
- finally runs unconditionally for resource cleanup.
5.3. 3. Custom Application Warning Flags (Custom Exceptions)
Definition: You can create custom error classes to represent specific business rule violations in your application.
Core Working Principles:
- Extending
Exception: Create a new class extending `Exception` to represent custom domain errors (e.g., `InvalidAgeException`). - The
throwKeyword: Used to manually trigger an error when a business rule fails.
// Custom exception class
public class LowBalanceException extends Exception {
public LowBalanceException(String message) {
super(message);
}
}
5-Marks Exam Scoring Points
- Custom exceptions encapsulate business rule violations.
- Use throw to trigger exceptions manually.
- Pass error messages to super(message) for stack trace reporting.
✍️ Chapter 5 Reference Exercises & Review Problems
1. Data Protection: Marking fields `private` prevents outside code from accidentally setting invalid data (like setting a student's age to -50!).
2. Controlled Access: You provide `public` getter and setter methods to inspect or update values safely with validation checks!
- The `finally` block **always executes**, regardless of whether an error occurred or not.
- It is used to close important system resources (like closing database connections or closing opened files) so system memory is never leaked.