Handling exceptions is an essential skill for writing robust Java applications. Java provides two important keywordsโthrow
and throws
โfor dealing with exceptions. While they may look similar, they serve different purposes in exception handling.
In this guide, weโll break down the differences between throw
and throws
, understand when to use each, and explore real-world examples to solidify the concepts.
1๏ธโฃ What is throw
in Java?
๐น The throw
keyword is used to explicitly throw an exception within a method or block of code.
๐น It is typically used to raise custom or built-in exceptions manually.
๐น Once an exception is thrown using throw
, the program execution stops unless the exception is caught using a try-catch
block.
โ
Syntax of throw
throw new ExceptionType("Error Message");
โ
Example: Using throw
to Manually Trigger an Exception
public class ThrowExample {
public static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above");
}
System.out.println("Welcome! You are eligible.");
}
public static void main(String[] args) {
validateAge(16); // ๐จ Throws IllegalArgumentException
}
}
๐น Key Takeaways for throw
โ๏ธ Used inside a method to manually throw an exception.
โ๏ธ Can be used to raise both checked and unchecked exceptions.
โ๏ธ Once thrown, it must be handled using a try-catch block or propagated using throws
.
2๏ธโฃ What is throws
in Java?
๐น The throws
keyword is used in a method signature to indicate that a method may throw one or more exceptions.
๐น It does not handle the exception itself but informs the caller that the method might generate an exception.
๐น The calling method must handle the exception using a try-catch
block or propagate it further using throws
.
โ
Syntax of throws
returnType methodName() throws ExceptionType {
// Method implementation
}
โ
Example: Using throws
to Propagate an Exception
import java.io.*;
public class ThrowsExample {
public static void readFile() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line = br.readLine();
System.out.println(line);
br.close();
}
public static void main(String[] args) {
try {
readFile(); // ๐จ Throws IOException
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
๐น Key Takeaways for throws
โ๏ธ Used in a method declaration to indicate potential exceptions.
โ๏ธ Can be used with multiple exceptions (comma-separated).
โ๏ธ Forces the caller to handle or propagate the exception.
3๏ธโฃ throw
vs throws
: Key Differences
Feature | throw |
throws |
---|---|---|
Definition | Used to explicitly throw an exception | Declares exceptions that a method may throw |
Where Itโs Used | Inside a method or block | In the method signature |
Type of Keyword | Statement (used inside method) | Declaration (used in method signature) |
Number of Exceptions | Can throw one exception at a time | Can declare multiple exceptions (comma-separated) |
Exception Handling | Needs to be caught with try-catch or propagated |
Forces the caller to handle the exception |
Example Usage | throw new IOException("Error"); |
public void readFile() throws IOException {} |
4๏ธโฃ Real-World Examples of throw
and throws
๐ Example 1: Banking Application (Using throw
)
Letโs say we have a banking system where users cannot withdraw more money than they have in their account.
public class BankAccount {
private double balance = 5000;
public void withdraw(double amount) {
if (amount > balance) {
throw new IllegalArgumentException("Insufficient funds! Withdrawal denied.");
}
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " + balance);
}
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.withdraw(6000); // ๐จ Throws IllegalArgumentException
}
}
๐ How It Works?
- The method checks if
amount > balance
. - If yes, it throws an
IllegalArgumentException
. - This prevents users from withdrawing more than available funds.
๐ Example 2: File Handling (Using throws
)
Now, letโs say we need to read a file from disk, and thereโs a possibility that the file may not exist.
import java.io.*;
public class FileReaderExample {
public static void readFile() throws IOException {
FileReader file = new FileReader("data.txt"); // May throw IOException
BufferedReader br = new BufferedReader(file);
System.out.println(br.readLine());
br.close();
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
๐ How It Works?
- The method
readFile()
declaresthrows IOException
, meaning it may generate an exception. - The caller (
main
method) must handle the exception with atry-catch
block.
5๏ธโฃ Best Practices for Using throw
and throws
โ๏ธ Use throw
for specific error conditions inside methods.
โ๏ธ Use throws
to indicate possible exceptions and let the caller handle them.
โ๏ธ Never declare unchecked exceptions (RuntimeException
) with throws
โitโs unnecessary.
โ๏ธ Use meaningful exception messages when throwing exceptions.
โ๏ธ Avoid using throws
excessivelyโhandle exceptions properly when possible.
๐ฏ Conclusion
Both throw
and throws
play an important role in Java exception handling:
๐น throw
is used to manually trigger an exception within a method.
๐น throws
is used to declare exceptions that may be thrown by a method.
๐น throw
stops execution immediately, while throws
forces the caller to handle exceptions.
Understanding their differences will help you write cleaner, more maintainable code and handle exceptions efficiently in Java applications. ๐
Did this guide help you? Let me know in the comments! ๐
Top comments (0)