throw
vs throws
in Java (With Real-Life Examples)
Java provides robust exception handling using try
, catch
, throw
, throws
, and finally
. Among these, throw
and throws
often confuse beginners. In this post, we'll break down their real-time differences, practical syntax, and usage in real-world Java projects.
🔹 1. Basic Difference
Feature | throw |
throws |
---|---|---|
Purpose | Used to throw an exception manually | Declares that a method can throw an exception |
Position | Used inside a method | Declared with method signature |
Syntax | throw new ExceptionType("msg"); |
public void method() throws ExceptionType {} |
Number Allowed | Only one exception object can be thrown | Can declare multiple exceptions |
Object Required | Yes, needs an object of Throwable class |
No object required |
🔹 2. Syntax Examples
// Using throw
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}
}
// Using throws
public void readFile(String filePath) throws IOException {
FileReader fr = new FileReader(filePath); // might throw IOException
}
🔹 3. Real-Time Project Example: Banking System
Let’s assume we are building a banking microservice.
✅ throw
Example
public void withdraw(double amount) {
if (amount > balance) {
throw new InsufficientFundsException("Insufficient balance");
}
balance -= amount;
}
-
Use Case: You manually check a condition and throw an exception to stop the process if it fails.
-
Real-Time Benefit: Helps enforce business rules clearly (like balance checks).
✅ throws
Example
public void processLoanApplication(String filePath) throws IOException {
// Reading a document
FileInputStream fis = new FileInputStream(filePath);
// Business logic
}
-
Use Case: You’re dealing with checked exceptions from Java IO or JDBC APIs.
-
Real-Time Benefit: Declares that the caller must handle or propagate it further.
🔹 4. Combined Example
public void applyForLoan(String userId, String documentPath) throws IOException {
if (!isEligible(userId)) {
throw new IllegalArgumentException("User not eligible for loan");
}
processLoanApplication(documentPath); // throws IOException
}
➕ Explanation:
-
throw
is used for business rule failure. -
throws
is used for possible checked exception from external resources (file, DB, etc).
🔹 5. Best Practices
-
Use
throw
when a method detects an exceptional situation and wants to fail fast. -
Use
throws
to delegate responsibility to the caller for handling expected exceptions. -
Always prefer custom exceptions (like
InsufficientFundsException
) for clear error handling.
💡 Fun Tip (for Reels or Shorts):
“
throw
is like yelling: 'Hey! Something’s wrong!' 🎯
throws
is like politely saying: 'Hey caller, you might want to handle this issue.' 🤝”
🔚 Conclusion
Understanding the difference between throw
and throws
is crucial for writing clean and effective Java code. Whether you're building microservices, reading files, or validating user input, knowing when to use throw
or throws
ensures your application handles errors gracefully.
Happy coding! 🚀
No comments:
Post a Comment