🧭 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 exceptioncatch: 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 tracetoString(): Exception name and descriptiongetMessage(): Only the description of the exception
How JVM Handles Exceptions
- When an exception occurs, the method creates an Exception Object (contains name, description, and current program state)
- JVM searches the call stack in reverse order to find an appropriate exception handler
- If found, passes the exception to the handler
- 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
FileServicemethods with appropriate exception handling
- Examples:
- 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
Productobjects and store inproductCatalog - File data is guaranteed valid; no validation required
- Read from
- 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
NumberFormatExceptionand skip invalid rows - Calculate: subtotal, discountValue, finalCost
- Track totals:
totalQuantity,totalFinalCost,totalDiscountValue,totalInvalidLines
- Read from order file (format:
- Part 3 - Generate Report: Implement
saveReport()method- Format: Summary report with all calculated totals
- Deadline: See repository for details
🔗 Repository Links
| Repository | Description |
|---|---|
| 📂 WS-05-exceptions-and-file-handling | Workshop: Practice exception handling and learn file operations (non-graded) |
| 📂 HW-06-exceptions-and-file-handling | Assignment: Build a sales report system with CSV processing |
🌐 Additional Resources
- Oracle Java Tutorials - Exceptions
- Java File I/O Documentation
- Java CSV Parsing Guide
- JSON Parsing with Java
⏩ 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.