Exception handling is a powerful mechanism in Java that handles runtime errors and maintains the normal flow of application execution. Among the tools Java provides for exception handling, two often confused keywords are throw and throws.
In this blog, we’ll break down the concepts of throw and throws, look at how they’re used, and go through clear examples to make sure you understand them deeply and confidently.
Prerequisite: What is an Exception?
Before jumping into throw and throws, let’s quickly revise what an exception is.
An exception is an unwanted or unexpected event that disrupts the normal flow of a program.
Java provides a robust exception-handling mechanism with five key keywords:
trycatchfinallythrowthrows
We already covered try, catch, and finally in earlier tutorial here. Let’s now focus on the last two: throw and throws.
What is throw in Java?
The throw keyword is used to explicitly throw an exception from your code, whether it’s a built-in exception or a user-defined exception.
Syntax:
throw new ExceptionType("Error Message");
Rules:
- Only one object can be thrown at a time.
- The object must be of type
Throwableor a subclass (likeExceptionorError). - It is used inside a method or block of code to trigger an exception conditionally.
Example 1: Using throw with a built-in exception
public class ThrowExample {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("You are not eligible to vote.");
} else {
System.out.println("You are eligible to vote.");
}
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: You are not eligible to vote.
at ThrowExample.main(ThrowExample.java:6)
Explanation:
- Here, we manually check if
ageis less than 18. - If it is, we throw an
ArithmeticException. - This interrupts the program and outputs the exception message.
Example 2: Throwing a Custom Exception
Java lets you create your own exceptions, known as custom exceptions, when the built-in ones don’t describe your error situation well enough.
This gives your code clarity, meaning, and improves debugging.
In this post, you’ll learn:
- Why and when to use custom exceptions
- How to create and throw one
- A unique example: ATM withdrawal limit enforcement
// Custom exception class
public class WithdrawalLimitExceededException extends Exception {
public WithdrawalLimitExceededException(String message) {
super(message);
}
}
public class ATM {
private static final int DAILY_LIMIT = 10000;
public void withdraw(int amount) throws WithdrawalLimitExceededException {
if (amount > DAILY_LIMIT) {
throw new WithdrawalLimitExceededException("❌ Withdrawal limit of ₹10,000 exceeded. Requested: ₹" + amount);
} else {
System.out.println("✅ Please collect your cash: ₹" + amount);
}
}
public static void main(String[] args) {
ATM userATM = new ATM();
try {
userATM.withdraw(12000); // Trying to withdraw more than the limit
} catch (WithdrawalLimitExceededException e) {
System.out.println("🚨 Exception: " + e.getMessage());
}
}
}
Output:
🚨 Exception: ❌ Withdrawal limit of ₹10,000 exceeded. Requested: ₹12000
Explanation:
- Custom Exception Class:
WithdrawalLimitExceededExceptiongives context-specific information about what went wrong. - Validation Logic:
Inside thewithdrawmethod, we check if the requested amount exceeds the limit. - Throwing the Exception:
If the rule is violated, the custom exception is thrown using thethrowkeyword. - Catching and Handling:
In themain()method, we usetry-catchto handle this situation and show a user-friendly error message.
Common Exceptions Used with throw:
| Exception Class | Used For |
|---|---|
ArithmeticException | Illegal arithmetic operations (like divide by zero) |
NullPointerException | Accessing methods/fields on null objects |
IllegalArgumentException | Passing illegal or inappropriate arguments |
CustomException | Your own exception classes (covered below!) |
What is throws in Java?
The throws keyword is used in a method signature to declare exceptions that a method might throw but doesn’t handle itself.
It tells the compiler and caller of the method to be ready to handle those exceptions.
Syntax:
returnType methodName() throws ExceptionType1, ExceptionType2 {
// method code
}
Example 3: User Email Validation in a Registration System
Suppose you’re building a user registration feature. You want to check if the user entered a valid email address. If not, your method should throw an exception back to the main program.
import java.io.FileReader;
import java.io.IOException;
public class ThrowsOnlyExample {
// Method declares it might throw IOException
public static void readFile() throws IOException {
FileReader file = new FileReader("data.txt"); // May throw IOException
System.out.println("✅ File opened successfully.");
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("🚨 Error: " + e.getMessage());
}
}
}
Output:
🚨 Error: data.txt (No such file or directory)
How it works:
- The method
readFile()doesn’t usethrow, but it might cause aFileNotFoundException, which is a checked exception. - So we declare it using
throws IOException. - The actual throwing is done internally by Java’s FileReader class.
Example 4: Bank Loan Processing with Credit Score Validation
In a banking app, a user can apply for a loan. But if their credit score is below 650, the loan is denied. We’ll create a method to check credit score, and throw an exception if it’s too low.
// Custom exception for low credit score
class LowCreditScoreException extends Exception {
public LowCreditScoreException(String message) {
super(message);
}
}
public class LoanApplication {
public void processLoan(int creditScore) throws LowCreditScoreException {
if (creditScore < 650) {
throw new LowCreditScoreException("❌ Loan Denied: Credit Score too low (" + creditScore + ")");
}
System.out.println("✅ Loan Approved for Credit Score: " + creditScore);
}
public static void main(String[] args) {
LoanApplication loan = new LoanApplication();
try {
loan.processLoan(580); // Low credit score
} catch (LowCreditScoreException e) {
System.out.println("🚨 Exception: " + e.getMessage());
}
}
}
Output:
🚨 Exception: ❌ Loan Denied: Credit Score too low (580)
How it works:
processLoan()method uses thethrowskeyword to inform the caller that it might throw aLowCreditScoreException.- In
main(), the exception is handled using atry-catchblock. - This approach keeps business rules clean and reusable.
When to Use throw vs throws
| Feature | throw | throws |
|---|---|---|
| Purpose | To explicitly throw an exception | To declare that a method might throw exceptions |
| Location | Inside a method or block | In method declaration |
| Syntax | throw new ExceptionType("message"); | method() throws ExceptionType |
| Used For | Actual exception object creation | Warning the compiler/caller |
| Count | Only one object can be thrown | Multiple exception types can be declare |
Best Practices
- Use
throwwhen you want to trigger an exception manually. - Use
throwsto signal that a method might cause an exception. - Always use
try-catchor declarethrowswhen dealing with checked exceptions. - Don’t overuse exceptions for flow control (e.g., don’t use them instead of
if-elseunnecessarily).
Summary
throwis used to explicitly throw an exception object.throwsis used to declare the possibility of exceptions in a method.- Always understand the difference between checked and unchecked exceptions.
- Use
try-catchor declare withthrowsbased on your scenario. throw= trigger exception,throws= inform compiler.
Final Tip
Mastering exception handling is crucial to writing robust and error-resistant Java applications. Understanding when and how to use throw and throws is a major step in that journey.
So practice writing small programs where you create your own exceptions, throw them, and handle them using throws or try-catch. This will cement your understanding and help you become a confident Java developer.
❓ FAQs on throw and throws in Java
1. What is the difference between throw and throws in Java?
**throw**is used to actually throw an exception (either built-in or custom) during the execution of code.**throws**is used in the method declaration to indicate that the method may throw an exception and does not handle it itself.
2. Can we use throw without throws?
Yes, but only if you’re throwing an unchecked exception (like NullPointerException, ArithmeticException, etc.).
If you throw a checked exception, you must also declare it using throws in the method signature.
3. Can a method have multiple exceptions in throws?
Yes, you can declare multiple exceptions using a comma-separated list:
public void readData() throws IOException, SQLException {
// code
}
4. Is it mandatory to handle exceptions declared with throws?
✅ Yes for checked exceptions — you must either catch them or declare further using throws.
❌ No for unchecked exceptions — the compiler won’t force you to handle them.
5. Can we use throw inside a try block?
✅ Yes, you can throw an exception inside a try block and catch it in the catch block:
try {
throw new IllegalArgumentException("Invalid input");
} catch (IllegalArgumentException e) {
System.out.println("Caught: " + e.getMessage());
}
6. Can we throw multiple exceptions using throw?
❌ No, you can only throw one exception object at a time:
throw new IOException("File error"); // Valid
// throw new IOException(), new SQLException(); // Invalid
7. Can constructors also use throws?
✅ Yes, constructors can declare exceptions with throws, just like methods:
public MyClass() throws IOException {
FileReader file = new FileReader("data.txt");
}
8. Can we rethrow an exception in Java?
✅ Yes, you can catch an exception and throw it again:
try {
// some code
} catch (IOException e) {
throw e; // rethrowing the same exception
}
9. What happens if you don’t handle a thrown checked exception?
❌ If you throw a checked exception without declaring it using throws or handling it in a try-catch, your code won’t compile.
10. Is it good practice to use throws everywhere instead of try-catch?
⚠️ Not always. Use throws when:
- You want the caller to decide how to handle the exception.
- You’re working with API design or library development.
Use try-catch when:
- You want to handle the error immediately.
- You need to show a user-friendly message or recover from the error.