🧭 Topic: Exceptions & Files

Quick Overview :

This topic covers Java’s exception handling mechanisms, including the hierarchy of exceptions, checked vs unchecked exceptions, try-catch blocks, and the throws keyword. It also introduces file operations including reading, writing, and parsing data, with practical applications in CSV processing and report generation.


📌 Covered in This Topic

Introduction to Exceptions & Errors

  • Exception: An unwanted or unexpected event during program execution
  • Error: Irrecoverable conditions beyond programmer’s control
    • Examples: JVM running out of memory, stack overflow, library incompatibility
    • Should not try to handle errors
  • Key Difference: Errors are serious problems that should not be caught; Exceptions are conditions that a reasonable application might try to catch

Exception Hierarchy

  • Throwable (root class)
    • Error (critical system issues)
    • Exception (conditions that can be handled)
      • RuntimeException (unchecked exceptions)
      • Other exceptions (checked exceptions)

Types of Exceptions

Checked Exceptions:

  • Checked at compile-time
  • Must be handled or declared with throws
  • Examples: IOException, FileNotFoundException, SQLException

Unchecked Exceptions:

  • Not checked at compile-time (subclasses of RuntimeException)
  • Occur due to programming errors
  • Examples: ArithmeticException, NullPointerException, NumberFormatException, IllegalArgumentException

Exception Handling Mechanisms

Try-Catch Block:

  • try: Code that might throw an exception
  • catch: Handler for specific exception types
  • Important: Simply catching and printing the message hides the error from the caller - better to rethrow or fully handle

Throws Keyword:

  • Declares that a method might throw exceptions
  • Caller must handle the exception

Throw Keyword:

  • Explicitly throws an exception

Exception Information Methods

  • printStackTrace(): Exception name, description, and full stack trace
  • toString(): Exception name and description
  • getMessage(): Only the description of the exception

How JVM Handles Exceptions

  1. When an exception occurs, the method creates an Exception Object (contains name, description, and current program state)
  2. JVM searches the call stack in reverse order to find an appropriate exception handler
  3. If found, passes the exception to the handler
  4. If not found, hands to the default exception handler, which terminates the program abnormally

File Handling in Java

  • Addressing Modes: Relative and absolute file paths
  • Creating Files: Programmatically creating files
  • Deleting Files: Safely removing files
  • Reading Files: Using Java IO classes to read text files
  • Writing Files: Writing content to files
  • Parsing JSON: Basic techniques for working with JSON files in Java

CSV Data Processing

  • Reading CSV files with proper parsing
  • Validating data (numeric ranges, existence checks)
  • Processing invalid data with try-catch
  • Generating reports with calculated results

📑 Slides & Materials


🛠️ Workshop & Assignments

💬 Workshop: Exceptions & File Handling

  • 📂 WS-05-exceptions-and-file-handling Repository
  • Structure: Demo programs and guided exercises
  • Section 1 - Exception Handling: Analyze code that produces runtime exceptions
    • Examples: NullPointerException, IllegalArgumentException, ArithmeticException, NumberFormatException, IllegalStateException
    • Modify FileService methods with appropriate exception handling
  • Section 2 - File Handling Guide: Instructional reference material
    • Topics: AddressingModes, CreatingFiles, DeletingFiles, ReadingFiles, WritingFiles, ParsingJson
  • Note: Not mandatory, no grading - purely for learning

🧮 Assignment: Sales Report System

  • 📂 HW-06-exceptions-and-file-handling Repository
  • Objective: Build a sales report system with CSV processing and report generation
  • Part 1 - Load Product Data: Implement loadProducts() method
    • Read from products.csv (format: [productId],[name],[price])
    • Create Product objects and store in productCatalog
    • File data is guaranteed valid; no validation required
  • Part 2 - Process Order File: Implement processFile() method
    • Read from order file (format: [productId],[quantity],[discountPercent])
    • Validate: quantity (integer > 0), discountPercent (0-99), productId exists
    • Use try-catch to handle NumberFormatException and skip invalid rows
    • Calculate: subtotal, discountValue, finalCost
    • Track totals: totalQuantity, totalFinalCost, totalDiscountValue, totalInvalidLines
  • Part 3 - Generate Report: Implement saveReport() method
    • Format: Summary report with all calculated totals
  • Deadline: See repository for details

RepositoryDescription
📂 WS-05-exceptions-and-file-handlingWorkshop: Practice exception handling and learn file operations (non-graded)
📂 HW-06-exceptions-and-file-handlingAssignment: Build a sales report system with CSV processing

🌐 Additional Resources


⏩ Navigation


Tip :

Exception handling is critical for building robust applications. Always handle exceptions at the appropriate level - don’t just catch and ignore them. When processing data from external sources, use try-catch blocks to gracefully handle invalid input without crashing the entire program. The “fail fast, recover gracefully” approach will save you from many headaches in production systems! Also, practice file operations by creating sample files and testing your code with various edge cases.