DEV Community

Cover image for ๐Ÿš€ throw vs throws in Java: Understanding the Key Differences
Arkadipta kundu
Arkadipta kundu

Posted on

๐Ÿš€ throw vs throws in Java: Understanding the Key Differences

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");
Enter fullscreen mode Exit fullscreen mode

โœ… 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
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น 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
}
Enter fullscreen mode Exit fullscreen mode

โœ… 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());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น 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
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” 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());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” How It Works?

  • The method readFile() declares throws IOException, meaning it may generate an exception.
  • The caller (main method) must handle the exception with a try-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)