Throw and throws are important keywords in Java Exception Handling. They allow developers to create, declare, and manage exceptions more effectively. While try, catch, and finally handle exceptions after they occur, throw and throws are used to generate exceptions and inform other parts of the program that an exception may occur.
Understanding throw and throws is essential for building robust Java applications, Android apps, enterprise software, and large-scale systems that require proper error handling.
What is throw in Java?
The throw keyword is used to explicitly create and throw an exception.
Instead of waiting for Java to generate an exception automatically, developers can manually generate an exception whenever required.
Syntax
throw new ExceptionType("Error Message");
The throw statement immediately stops normal program execution and transfers control to an appropriate catch block.
Why Use throw?
The throw keyword is useful when:
- Validating user input
- Enforcing business rules
- Preventing invalid operations
- Creating custom error conditions
- Improving program reliability
It gives developers complete control over exception generation.
Example of throw
public class Main {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Not Eligible");
}
System.out.println("Access Granted");
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: Not Eligible
The exception is manually generated because the condition is not satisfied.
Handling throw with try-catch
The exception generated by throw can be handled using a try-catch block.
Example
public class Main {
public static void main(String[] args) {
try {
int age = 15;
if (age < 18) {
throw new ArithmeticException("Not Eligible");
}
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
Output
Not Eligible
The exception is caught and handled gracefully.
Throwing Different Types of Exceptions
ArithmeticException
throw new ArithmeticException("Invalid Calculation");
NullPointerException
throw new NullPointerException("Object Cannot Be Null");
IllegalArgumentException
throw new IllegalArgumentException("Invalid Input");
Java allows developers to throw both built-in and custom exceptions.
What is throws in Java?
The throws keyword is used in a method declaration to indicate that the method may generate one or more exceptions.
Instead of handling the exception inside the method, throws passes responsibility to the method caller.
Syntax
returnType methodName() throws ExceptionType {
// code
}
The caller must handle or further declare the exception.
Why Use throws?
The throws keyword is useful when:
- A method cannot handle an exception itself
- Exception handling should occur elsewhere
- Multiple methods share exception handling logic
- Working with checked exceptions
It improves code organization and maintainability.
Example of throws
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Not Eligible");
}
System.out.println("Eligible");
}
public static void main(String[] args) {
checkAge(15);
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: Not Eligible
The method declares that it may throw an exception.
Handling a Method with throws
Example
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Not Eligible");
}
}
public static void main(String[] args) {
try {
checkAge(15);
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
Output
Not Eligible
The exception is handled by the calling method.
Using throws with Checked Exceptions
Checked exceptions must be handled or declared using throws.
Example:
import java.io.IOException;
public class Main {
static void readFile() throws IOException {
throw new IOException("File Not Found");
}
public static void main(String[] args) {
try {
readFile();
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Output
File Not Found
This is a common use case for the throws keyword.
Multiple Exceptions with throws
A method can declare multiple exceptions.
Example
public void processData()
throws IOException, ArithmeticException {
}
This indicates that either exception may occur during execution.
Difference Between throw and throws
| Feature | throw | throws |
|---|---|---|
| Purpose | Generates an exception | Declares an exception |
| Used In | Method body | Method declaration |
| Followed By | Exception object | Exception class |
| Quantity | One exception at a time | Multiple exceptions allowed |
| Responsibility | Creates exception | Passes exception handling responsibility |
Both keywords work together but serve different purposes.
Real-World Example
Banking System
public class Bank {
static void withdraw(double balance, double amount)
throws ArithmeticException {
if (amount > balance) {
throw new ArithmeticException(
"Insufficient Balance"
);
}
System.out.println("Withdrawal Successful");
}
}
Usage:
try {
Bank.withdraw(5000, 7000);
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
Output
Insufficient Balance
This type of validation is common in financial applications.
Applications of throw and throws
These keywords are widely used in:
- Banking systems
- Android applications
- E-commerce platforms
- Database systems
- User authentication systems
- Enterprise software
- File management applications
- Web services
Most professional Java applications use throw and throws extensively.
Common Beginner Mistakes
Confusing throw and throws
Incorrect understanding:
- throw creates an exception
- throws declares an exception
Both have different purposes.
Forgetting Exception Object with throw
Incorrect:
throw ArithmeticException;
Correct:
throw new ArithmeticException();
An exception object must be created.
Ignoring Checked Exceptions
Methods that generate checked exceptions must either:
- Handle them using try-catch
- Declare them using throws
Using throws Unnecessarily
Some developers declare exceptions that will never occur.
Only declare relevant exceptions.
Best Practices
When using throw and throws:
- Throw meaningful exceptions
- Provide clear error messages
- Use specific exception types
- Avoid generic Exception where possible
- Handle exceptions at the appropriate level
- Document important exceptions
These practices improve code readability and maintainability.
Importance of throw and throws
The throw and throws keywords are important because they:
- Improve error handling
- Enforce business rules
- Increase application reliability
- Simplify debugging
- Support modular programming
- Enable professional exception management
They are essential tools for building robust Java applications.
Conclusion
The throw and throws keywords play a vital role in Java Exception Handling. The throw keyword is used to explicitly generate exceptions, while the throws keyword declares exceptions that a method may produce. Together, they help developers create reliable, maintainable, and professional software by ensuring that errors are handled in a structured and predictable manner. Mastering throw and throws is an important step toward becoming a skilled Java developer and building high-quality applications.