Object Oriented Programming With JavaUnit 69 min read
Exception Handling: Errors, Exceptions, Try-Catch, Custom Exceptions & File I/O
Unit 6 of Object Oriented Programming With Java covers exception handling mechanisms in Java, including error vs. exception, checked vs. unchecked exceptions, try-catch-finally, custom exceptions, and file I/O operations with exception handling. This note explains how to handle runtime errors gracefully, create custom
TAKEAWAYS:
- Exceptions vs. Errors: Exceptions are recoverable runtime issues (e.g.,
NullPointerException), while errors (e.g.,OutOfMemoryError) are fatal and unrecoverable. - Checked vs. Unchecked: Checked exceptions (e.g.,
IOException) must be declared withthrowsor handled intry-catch, while unchecked exceptions (e.g.,ArithmeticException) are optional. - Exception Handling Flow: Use
try-catch-finallyblocks to isolate error-prone code, execute recovery logic, and ensure cleanup (e.g., closing files). - Custom Exceptions: Extend
ExceptionorRuntimeExceptionto create domain-specific exceptions (e.g.,InvalidPhoneNumberException). - File I/O with Exceptions: Always handle
FileNotFoundExceptionandIOExceptionwhen reading/writing files to avoid crashes. throwvs.throws:throwexplicitly throws an exception, whilethrowsdeclares exceptions a method might propagate.
1. Introduction to Exceptions and Errors
1.1 Definitions
- Error: A serious system-level issue (e.g., JVM crash, hardware failure) that cannot be recovered programmatically. Example:
OutOfMemoryError,StackOverflowError. - Exception: A runtime issue that can be handled (e.g., invalid user input, file not found). Example:
NullPointerException,ArithmeticException. - Fault: A permanent failure (e.g., corrupted data).
1.2 Why Handle Exceptions?
- Graceful Degradation: Prevents program crashes (e.g., a banking app should not terminate if a user enters invalid input).
- Debugging: Logs errors for developers to fix issues later.
- User Experience: Shows meaningful messages (e.g., "Invalid phone number. Must be 10 digits.").
- Resource Management: Ensures resources (e.g., files, database connections) are released properly.
2. Types of Exceptions
2.1 Classification of Exceptions
classDiagram
class Throwable {
<<abstract>>
+String getMessage()
}
class Error {
<<subclass>>
+OutOfMemoryError
+StackOverflowError
}
class Exception {
<<subclass>>
+IOException
+SQLException
}
class RuntimeException {
<<subclass>>
+NullPointerException
+ArithmeticException
}
class CheckedException {
<<subclass>>
+IOException
+ClassNotFoundException
}
class UncheckedException {
<<subclass>>
+RuntimeException
}
Throwable <|-- Error
Throwable <|-- Exception
Exception <|-- RuntimeException
Exception <|-- CheckedException
RuntimeException <|-- UncheckedException2.2 Checked vs. Unchecked Exceptions
| Feature | Checked Exception | Unchecked Exception |
|---|---|---|
| Inheritance | Extends Exception (not RuntimeException) |
Extends RuntimeException or Error |
| Handling | Must be handled with try-catch or throws |
Optional to handle |
| Examples | IOException, SQLException, ClassNotFoundException |
NullPointerException, ArrayIndexOutOfBoundsException |
| Compile-Time Check | Yes (compiler forces handling) | No (compiler ignores) |
| Recovery | Often recoverable (e.g., retry file read) | Often programming errors (e.g., logic bug) |
3. Exception Handling Mechanisms
3.1 try-catch-finally Block
try {
// Risky code (may throw an exception)
FileReader file = new FileReader("nonexistent.txt");
} catch (FileNotFoundException e) {
// Handle the exception
System.out.println("File not found: " + e.getMessage());
} finally {
// Cleanup code (always executes)
System.out.println("Cleanup complete.");
}
Visual Trace of Execution:
flowchart TD
A["Start"] --> B["try block: Open file"]
B -->|"File exists"| C["Success: Read file"]
B -->|"File not found"| D["catch block: Handle FileNotFoundException"]
C --> E["finally block: Close file"]
D --> E
E --> F["End"]3.2 throw vs. throws
throw: Explicitly throws an exception inside a method.if (age < 0) { throw new IllegalArgumentException("Age cannot be negative."); }throws: Declares exceptions a method might throw (does not handle them).public void readFile() throws IOException { FileReader file = new FileReader("data.txt"); }
4. Custom Exceptions
4.1 Creating a Custom Exception
// Custom exception for invalid phone numbers
class InvalidPhoneNumberException extends Exception {
public InvalidPhoneNumberException(String message) {
super(message);
}
}
Example Usage:
public class Mobile {
private String type;
private String phoneNo;
public Mobile(String type, String phoneNo) throws InvalidPhoneNumberException {
this.type = type;
if (phoneNo.length() != 10) {
throw new InvalidPhoneNumberException("Phone number must be 10 digits.");
}
this.phoneNo = phoneNo;
}
}
Visual Trace:
flowchart TD
A["Start"] --> B["Check phoneNo length"]
B -->|"Length != 10"| C["throw InvalidPhoneNumberException"]
B -->|"Length == 10"| D["Set phoneNo"]
C --> E["Handle exception in caller"]
D --> F["End"]5. File Handling with Exception Handling
5.1 Reading/Writing Files Safely
import java.io.*;
public class FileHandler {
public static void main(String[] args) {
try {
// Writing to a file
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, TU Students!");
writer.close();
System.out.println("Successfully wrote to file.");
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
}
Visual Trace of File Operations:
sequenceDiagram
participant User
participant FileWriter
participant File
User->>FileWriter: new FileWriter("output.txt")
FileWriter->>File: Open file (creates if not exists)
User->>FileWriter: write("Hello...")
FileWriter->>File: Write data
User->>FileWriter: close()
FileWriter->>File: Flush & close6. Real-World Applications
6.1 eSewa: Handling Invalid Transactions
- Idea Used: Custom exceptions for invalid transactions (e.g., insufficient balance).
- How It Works:
- When a user tries to pay more than their balance, eSewa throws a
InsufficientFundsException. - The system catches it and shows: "Your balance is NPR 500. Transaction failed."
- When a user tries to pay more than their balance, eSewa throws a
6.2 Ncell: SIM Registration Validation
- Idea Used: Checked exceptions for invalid SIM details (e.g., non-Nepali citizen ID).
- How It Works:
public void registerSIM(String citizenID) throws InvalidCitizenIDException { if (!citizenID.matches("\\d{7}")) { throw new InvalidCitizenIDException("Invalid citizen ID format."); } // Proceed with registration }
6.3 Daraz: Order Processing Queue
- Idea Used: Exception handling for failed order deliveries.
- How It Works:
- If a delivery address is invalid, Daraz throws a
InvalidAddressException. - The system logs the error and notifies the customer: "Your order could not be delivered. Please check your address."
- If a delivery address is invalid, Daraz throws a
7. Worked Example: Bank Loan Interest Calculation
Problem: Write a program to calculate loan interest, throwing an exception if the interest rate is negative.
class InvalidInterestRateException extends Exception {
public InvalidInterestRateException(String message) {
super(message);
}
}
public class LoanCalculator {
public static double calculateInterest(double principal, double rate)
throws InvalidInterestRateException {
if (rate < 0) {
throw new InvalidInterestRateException("Interest rate cannot be negative.");
}
return principal * rate / 100;
}
public static void main(String[] args) {
try {
double interest = calculateInterest(100000, -5);
System.out.println("Interest: " + interest);
} catch (InvalidInterestRateException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Visual Trace:
flowchart TD
A["Start"] --> B["Check rate < 0"]
B -->|"Yes"| C["throw InvalidInterestRateException"]
B -->|"No"| D["Calculate interest"]
C --> E["catch block: Print error"]
D --> F["Print interest"]
E --> G["End"]
F --> G["End"]8. Exam Tips
Differentiate Clearly:
- Error vs. Exception: Errors are fatal; exceptions are recoverable.
- Checked vs. Unchecked: Checked exceptions require handling; unchecked do not.
throwvs.throws:throwis for throwing;throwsis for declaring.
Code Structure:
- Always use
try-catch-finallyfor file operations. - Custom exceptions should extend
Exception(checked) orRuntimeException(unchecked).
- Always use
Common Pitfalls:
- Forgetting to close resources (use
try-with-resourcesin Java 7+). - Catching too broad exceptions (e.g., catch
Exceptioninstead of specific types).
- Forgetting to close resources (use
File Handling:
- Handle
FileNotFoundExceptionandIOExceptionexplicitly. - Use
try-with-resourcesfor auto-closing files:try (FileWriter writer = new FileWriter("file.txt")) { writer.write("Data"); } // Automatically closes writer
- Handle
Real-World Scenarios:
- Relate exceptions to banking (invalid transactions), e-commerce (failed deliveries), or government systems (invalid citizen IDs).
Based on the TU BITM syllabus for Object Oriented Programming With Java (IT234), unit 6.
Discussion
Loading…