DEV Community

Cover image for Java Exception Handling:Understanding throw vs throws
KIRAN RAJ
KIRAN RAJ

Posted on

Java Exception Handling:Understanding throw vs throws

Exception Handling in Java: throw vs throws

When writing Java programs, errors can happen anytime — like dividing by zero, invalid input, or file issues.
To handle these situations properly, Java provides exception handling.

Two important keywords in Java exception handling are:

  • throw

  • throws


1.What is an Exception?

An exception is an unwanted event that stops the normal flow of a program.

Example:

int a = 10;
int b = 0;
int result = a / b; // ArithmeticException


2.What is throw in Java?

throw is used to manually create and throw an exception.

  • It is used inside a method.

✅ Syntax:

throw new ExceptionType("Error message");
Enter fullscreen mode Exit fullscreen mode

✅ Example:

public class Test {
    public static void main(String[] args) {
        int age = 15;

        if(age < 18){
            throw new ArithmeticException("Not eligible to vote");
        }

        System.out.println("Eligible");
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

If condition is true → exception is thrown manually

Program stops unless handled


  1. What is throws in Java?

throws is used to declare exceptions that a method might throw.

  • It is used in method signature.

✅ Syntax:

returnType methodName() throws ExceptionType
Enter fullscreen mode Exit fullscreen mode

✅ Example:

import java.io.*;

public class Test {
    public static void readFile() throws IOException {
        FileReader file = new FileReader("test.txt");
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch(IOException e){
            System.out.println("File not found");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

throws tells the compiler: "This method may cause an exception"

The caller must handle it using try-catch


4. Difference Between throw and throws

Feature throw throws

Usage Used to throw exception Used to declare exception
Location Inside method Method signature
Number Only one exception at a time Multiple exceptions allowed
Keyword Type Statement Declaration


💡 Real-Life Analogy

throw 👉 You actually throw a ball

throws 👉 You warn someone that you may throw a ball


5.When to Use?

✔ Use throw

When you want to create custom error conditions

For validation (age, input, etc.)

✔ Use throws

When method might cause checked exceptions

When you want caller to handle exception


Top comments (0)