For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
When it comes to exception handling in Java, two terms that often puzzle beginners are throw and throws. While they may look similar, they serve distinct purposes in error handling. Knowing the difference between throw and throws in Java is key to writing clean, robust, and maintainable code. One is used actually to throw an exception, and the other is used to declare an exception, and mixing them up can lead to confusing errors and unexpected behavior.
This beginner-friendly guide'll break down both keywords with simple explanations and practical code examples. You’ll learn when and how to use each and the common mistakes to avoid. Whether starting with Java programming or revisiting core concepts, this guide will help you understand these two terms clearly.
To learn Java more deeply and build a solid foundation, consider enrolling in top-rated online software engineering courses that offer structured learning and real-world projects.
Aspect | throw | throws |
Purpose | Used to explicitly throw an exception | Used to declare exceptions that a method might throw |
Location | Used inside method body | Used in method signature |
Syntax | throw objectOfThrowableType; | returnType methodName() throws ExceptionType1, ExceptionType2 {...} |
What follows | An object/instance of Throwable | Exception class names |
Number of exceptions | Can throw only one exception at a time | Can declare multiple exceptions |
Exception type | Can throw both checked and unchecked exceptions | Primarily used for checked exceptions |
Handling requirement | Must be enclosed in try-catch block or thrown further | Forces caller to handle or propagate the exception |
When used | Used when a specific condition warrants an exception | Used when a method contains code that might throw exceptions |
Example | throw new IOException("File not found"); | void readFile() throws IOException, FileNotFoundException {...} |
Effect | Immediately transfers control to catch block | Has no effect at runtime unless an exception occurs |
Advance your career with these proven skill-building programs.
The throw keyword in Java programming explicitly throws an exception from within a method or block of code. It's a mechanism for signaling that something unexpected has happened and normal program flow cannot continue.
throw throwableObject;
Where throwableObject is an instance of any class that inherits from the Throwable class.
Consider a banking application where you need to validate user input before processing a transaction. If a user attempts to withdraw a negative amount, this violates business logic and should trigger an exception.
public void validateWithdrawalAmount(double amount) {
// Check if amount is negative
if (amount <= 0) {
// Throw an IllegalArgumentException with a descriptive message
throw new IllegalArgumentException("Withdrawal amount must be positive");
}
// Code here will only execute if the amount is valid
System.out.println("Amount validation successful");
}
Output (if amount <= 0):
Exception in thread "main" java.lang.IllegalArgumentException: Withdrawal amount must be positive
This example demonstrates how the throw keyword creates and throws an exception when an invalid withdrawal amount is detected, immediately stopping the normal execution flow.
The throws keyword in Java is used in method declarations to indicate that the method might throw specific types of exceptions. It serves as a warning to callers of the method that they need to handle or propagate these exceptions.
returnType methodName(parameters) throws ExceptionType1, ExceptionType2, ... {
// Method body
}
In file handling operations, many things can go wrong - the file might not exist, might be locked, or the program might not have permission to access it. Methods that perform file operations typically declare these potential problems using the throws keyword.
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
// Method declaration with throws keyword
public static void readFile(String filePath) throws IOException {
FileReader reader = new FileReader(filePath);
// Code to read from the file
reader.close();
System.out.println("File read successfully");
}
public static void main(String[] args) {
try {
// Call to method that throws an exception
readFile("nonexistent.txt");
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}
Output:
Error reading file: nonexistent.txt (No such file or directory)
In this example, the readFile method declares that it might throw an IOException using the throws keyword. The calling method (main) handles this potential exception with a try-catch block.
Also read: Overloading vs Overriding in Java
Before diving deeper into the differences between throw and throws keywords in Java, let's establish some context about Java's exception handling system. Java's exception handling framework is designed to manage runtime errors in a structured manner, allowing programs to recover from unexpected situations.
An exception in Java represents an abnormal condition that disrupts the normal flow of program execution. These exceptions are objects that inherit from the Throwable class, forming a hierarchy of exception types that include:
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Method declares it might throw InsufficientFundsException
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be positive");
}
if (amount > balance) {
// Explicit throw of a custom exception
throw new InsufficientFundsException("Insufficient funds: " +
"Request: " + amount + ", Available: " + balance);
}
balance -= amount;
System.out.println("Withdrawal successful. New balance: " + balance);
}
// Custom exception class
public static class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
try {
account.withdraw(1500); // This will throw InsufficientFundsException
} catch (InsufficientFundsException e) {
System.out.println("Transaction failed: " + e.getMessage());
}
}
}
Output:
Transaction failed: Insufficient funds: Request: 1500.0, Available: 1000.0
This example demonstrates both concepts in action:
To fully comprehend the difference between throw and throws and throwable in Java, we need to understand what Throwable is. The Throwable class is the root class of Java's exception hierarchy.
Understanding when to use each keyword is vital for proper exception handling:
To make the most effective use of these keywords:
Understanding the difference between throw and throws in Java is essential for effective exception handling. The throw keyword is used within method bodies to create and throw exceptions when specific conditions occur, while the throws keyword appears in method signatures to declare what exceptions might be thrown by the method. Using these keywords appropriately helps create more robust, maintainable code by clearly communicating potential error conditions and ensuring they're properly handled.
By mastering these concepts, you'll be better equipped to write Java code that gracefully handles unexpected situations, making your applications more reliable and user-friendly.
The throw keyword is followed by an instance of a Throwable class (e.g., throw new IOException()), while the throws keyword is followed by one or more exception class names (e.g., void method() throws IOException, SQLException).
Yes, you can use both in the same method. The throws clause declares what exceptions the method might throw, and the throw statement actually throws the exception inside the method body.
No, the throws clause is not required when throwing unchecked exceptions (RuntimeException and its subclasses), though you can include it for documentation purposes.
Use throws when you want to delegate the responsibility of handling the exception to the calling method rather than handling it locally. This is useful when the current method doesn't have enough context to properly recover from the exception.
If a method calls another method that declares a checked exception with throws but doesn't handle it or propagate it further with its own throws clause, the code will not compile.
Yes, a method can declare that it throws exceptions even if it never actually throws them. This is sometimes done when implementing interfaces or for future-proofing code.
The throw keyword actually creates and propagates an exception object, while throws simply declares that a method might throw certain exceptions without actually doing the throwing.
No, only one exception can be thrown at a time with the throw keyword. However, multiple exception types can be declared with the throws keyword.
You'd use both: throws in the method signature to declare that your method might throw your custom exception, and throw inside the method to actually throw the exception when needed.
Yes, abstract methods can include a throws clause to declare what exceptions implementing methods might throw.
Yes, constructors can both throw exceptions using the throw keyword and declare exceptions using the throws keyword, just like regular methods.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.