ZeroToSky
Java Tutorial 73 of 143
Basics
  • Introduction
  • Download and Install Java
  • Download and Install IntelliJ IDEA, Eclipse
  • Creating First Java Application in IntelliJ IDEA
  • JDK vs JRE vs JVM
  • Print output
  • Taking Input
  • Identifiers
  • Keywords
  • Variables
  • Data Types
  • Literals
  • Wrapper Classes
  • Operators
  • Decision Making
  • Loops and Jump Statements
  • Project: Number Guessing Game

All 17 lessons →

Methods
  • Introduction
  • Static Methods vs Instance Methods
  • Access Modifiers
  • Command Line Arguments
  • Variable Arguments (Varargs)

All 5 lessons →

Arrays
  • Introduction
  • One Dimensional Arrays
  • Multidimensional Arrays
  • Array Class
  • Arrays Class

All 5 lessons →

Strings
  • Introduction
  • String
  • StringBuffer
  • StringBuilder
  • String Class Methods
  • StringJoiner
  • StringTokenizer

All 7 lessons →

OOP & Interface

All 14 lessons →

Collections
  • Collection class
  • Collection Interface
  • List Interface
  • ArrayList
  • LinkedList
  • Set Interface
  • HashSet
  • LinkedHashSet
  • TreeSet
  • Queue Interface
  • PriorityQueue
  • Deque
  • ArrayDeque
  • Map Interface in Java
  • HashMap
  • LinkedHashMap
  • TreeMap
  • Hashtable
  • Iterator
  • Comparable and Comparator

All 20 lessons →

Exception Handling

All 7 lessons →

Multithreading & Concurrency
  • Introduction
  • Thread Class
  • Runnable Interface
  • Thread Life Cycle
  • Thread Priority
  • Synchronization
  • Inter-Thread Communication
  • Executor Framework
  • Callable and Future
  • Concurrent Collections

All 10 lessons →

Java 8 Features
  • Lambda Expressions
  • Functional Interfaces
  • Method References
  • Stream API
  • Optional Class
  • Default and Static Methods in Interface
  • Date and Time API

All 7 lessons →

Advanced Java Concepts
  • File Handling
  • Serialization and Deserialization
  • Reflection API
  • Annotations
  • Garbage Collection
  • Memory Management
  • JVM Architecture
  • Class Loading
  • Networking
  • Regular Expressions

All 10 lessons →

JDBC
  • Introduction
  • JDBC Driver
  • JDBC Connection
  • Types of Statements in JDBC
  • Transactions
  • ResultSet
  • Metadata
  • Connection Pooling

All 8 lessons →

GUI & Desktop
  • AWT
  • Swing
  • JavaFX

All 3 lessons →

Web & Enterprise
  • Servlets
  • JSP
  • Spring Framework
  • Spring Boot
  • Hibernate
  • REST API Development

All 6 lessons →

Practice Projects
  • Project: Number Guessing Game
  • Project: Banking System
  • Project: Student Management System
  • Project: Library Management System
  • Project: Quiz Application

All 5 lessons →

Quiz and Coding Practice
  • Java Topic-wise Quiz
  • Coding Practice Problems
  • Java Basics Coding Practice Problems
  • Java Exercises

All 4 lessons →

Interview Questions
  • Core Java Interview Questions and Answers
  • Advanced Java Interview Questions and Answers
  • Java Interview Questions

All 3 lessons →

DSA & Competitive Programming
  • Arrays and Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Heap
  • Hashing
  • Sorting
  • Searching
  • Dynamic Programming
  • Roadmap for DSA in Java

All 12 lessons →

Java throw and throws

Learn the difference between Java throw and throws, how to explicitly throw exceptions, declare exceptions in methods, and handle checked and unchecked exceptions.

Gaurav 7 min read Sign in to save
On this page

Java throw and throws

In Java, throw and throws are keywords used for exception handling, but they serve different purposes.

  • throw is used to explicitly throw an exception from a method or block of code.
  • throws is used in a method declaration to specify that the method may pass one or more exceptions to its caller.

Understanding the difference between throw and throws is important when writing Java applications with proper exception handling.

What Is throw in Java?

The throw keyword is used to explicitly create and throw an exception.

Syntax

throw new ExceptionType("Error message");

For example:

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

        if (age < 18) {
            throw new IllegalArgumentException("Age must be at least 18");
        }

        System.out.println("Eligible");
    }
}

Here, the program explicitly throws an IllegalArgumentException when age is less than 18.

Output

Exception in thread "main" java.lang.IllegalArgumentException: Age must be at least 18

Why Use throw?

throw is useful when your application needs to detect an invalid condition and explicitly report it as an exception.

For example:

public class Main {

    static void withdraw(double balance, double amount) {
        if (amount > balance) {
            throw new IllegalArgumentException("Insufficient balance");
        }

        System.out.println("Withdrawal successful");
    }

    public static void main(String[] args) {
        withdraw(5000, 7000);
    }
}

The method explicitly throws an exception when the withdrawal amount exceeds the balance.


throw with a Custom Exception

You can also use throw with your own custom exception.

class InvalidAgeException extends Exception {

    public InvalidAgeException(String message) {
        super(message);
    }
}

The exception can then be thrown explicitly:

public class Main {

    static void checkAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or above");
        }

        System.out.println("Valid age");
    }

    public static void main(String[] args) {
        try {
            checkAge(15);
        } catch (InvalidAgeException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

Age must be 18 or above

Notice that this example uses both throw and throws.

  • throw actually creates and throws the exception.
  • throws declares that the method can pass the exception to its caller.

What Is throws in Java?

The throws keyword is used in a method declaration to specify exceptions that the method may throw.

Syntax

returnType methodName() throws ExceptionType {
    // method body
}

For example:

public void readFile() throws IOException {
    // file operations
}

This tells the caller that readFile() may throw an IOException.

The method itself does not necessarily handle the exception.


Example of throws

import java.io.IOException;

public class Main {

    static void readData() throws IOException {
        throw new IOException("Unable to read data");
    }

    public static void main(String[] args) {
        try {
            readData();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

Unable to read data

Here:

throws IOException

declares the possible exception, while:

throw new IOException(...)

actually throws the exception.


throw vs throws

The main difference is that throw is used to perform the throwing, while throws is used to declare the possibility of throwing.

Feature throw throws
Purpose Explicitly throws an exception Declares possible exceptions
Location Inside method/block Method declaration
Followed by An exception object Exception class names
Number Normally throws one exception at a time Can declare multiple exceptions
Used with Checked and unchecked exceptions Mainly important for checked exceptions
Responsibility Actually throws exception Passes responsibility to caller

Example

throw new IOException("File not found");

versus:

void readFile() throws IOException {
}

The first statement throws the exception.

The second declares that the method may throw it.


Using throw and throws Together

It is common to use both keywords in the same method.

class InvalidAgeException extends Exception {

    public InvalidAgeException(String message) {
        super(message);
    }
}

public class Main {

    static void validateAge(int age) throws InvalidAgeException {

        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or above");
        }

        System.out.println("Age is valid");
    }

    public static void main(String[] args) {

        try {
            validateAge(15);
        } catch (InvalidAgeException e) {
            System.out.println(e.getMessage());
        }
    }
}

The important part is:

static void validateAge(int age) throws InvalidAgeException

This declares the exception.

Inside the method:

throw new InvalidAgeException("Age must be 18 or above");

actually throws it.


throw with Checked Exceptions

A checked exception must be either:

  1. Handled using try-catch, or
  2. Declared using throws.

For example:

import java.io.IOException;

public class Main {

    static void process() throws IOException {
        throw new IOException("Processing failed");
    }

    public static void main(String[] args) {
        try {
            process();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

If process() did not handle or declare the IOException, the compiler would report an error.


throw with Unchecked Exceptions

Unchecked exceptions do not need to be declared using throws.

For example:

public class Main {

    static void validate(int number) {

        if (number < 0) {
            throw new IllegalArgumentException("Number cannot be negative");
        }
    }

    public static void main(String[] args) {
        validate(-10);
    }
}

IllegalArgumentException is an unchecked exception.

Therefore, this is valid:

throw new IllegalArgumentException("Invalid number");

without:

throws IllegalArgumentException

Although Java allows unchecked exceptions to be declared with throws, it is not required.


Multiple Exceptions with throws

A method can declare multiple exceptions using commas.

void process() throws IOException, SQLException {
    // code
}

For example:

import java.io.IOException;
import java.sql.SQLException;

public class DataService {

    void processData() throws IOException, SQLException {
        // operations that may throw either exception
    }
}

The caller must account for the checked exceptions according to Java's exception-handling rules.


Exception Propagation with throws

When a method does not handle a checked exception, it can declare it with throws and allow the caller to handle it.

Consider:

import java.io.IOException;

public class Main {

    static void method3() throws IOException {
        throw new IOException("Error occurred");
    }

    static void method2() throws IOException {
        method3();
    }

    static void method1() throws IOException {
        method2();
    }

    public static void main(String[] args) {

        try {
            method1();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

The flow is:

main()
  |
  v
method1()
  |
  v
method2()
  |
  v
method3()
  |
  v
IOException

The exception is propagated up the call stack until it is handled.


throw Inside try-catch

You can explicitly throw an exception inside a try block.

public class Main {

    public static void main(String[] args) {

        try {
            int age = 15;

            if (age < 18) {
                throw new IllegalArgumentException("Not eligible");
            }

            System.out.println("Eligible");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output:

Not eligible

This is useful when application-specific validation rules need to generate exceptions.


throw and finally

The throw keyword can also be used in code that has a finally block.

public class Main {

    public static void main(String[] args) {

        try {
            throw new RuntimeException("Something went wrong");
        } finally {
            System.out.println("Finally executed");
        }
    }
}

Output:

Finally executed
Exception in thread "main" java.lang.RuntimeException: Something went wrong

The exception is still propagated after the finally block executes.


Difference Between throw and return

throw and return have very different purposes.

return

Returns a value from a method:

return 100;

throw

Stops normal execution and transfers control to exception handling:

throw new RuntimeException("Error");

For example:

static int divide(int a, int b) {

    if (b == 0) {
        throw new ArithmeticException("Cannot divide by zero");
    }

    return a / b;
}

The method returns a value when the operation is valid and throws an exception when the input is invalid.


throw vs throws vs try-catch

These three concepts are closely related but have different responsibilities.

Keyword Purpose
throw Explicitly throws an exception
throws Declares exceptions that a method may pass to its caller
try-catch Handles an exception

Example:

static void validateAge(int age) throws Exception {

    if (age < 18) {
        throw new Exception("Invalid age");
    }
}

And the caller can handle it:

try {
    validateAge(15);
} catch (Exception e) {
    System.out.println(e.getMessage());
}

The complete flow is:

throw
  ↓
Exception generated
  ↓
throws
  ↓
Exception passed to caller
  ↓
try-catch
  ↓
Exception handled

Can throw Throw Multiple Exceptions?

A single throw statement throws one exception object.

For example:

throw new IllegalArgumentException("Invalid input");

However, a method can contain multiple throw statements:

static void validate(int value) {

    if (value < 0) {
        throw new IllegalArgumentException("Negative value");
    }

    if (value == 0) {
        throw new IllegalArgumentException("Zero is not allowed");
    }
}

Only the exception corresponding to the condition reached during execution is thrown.


Can throws Declare Multiple Exceptions?

Yes.

void process() throws IOException, SQLException, ClassNotFoundException {
    // code
}

Multiple exception types are separated using commas.


throw and throws with Custom Exceptions

Custom exceptions are one of the most common situations where both keywords are used together.

class InsufficientBalanceException extends Exception {

    public InsufficientBalanceException(String message) {
        super(message);
    }
}

Use the exception:

class BankAccount {

    private double balance = 5000;

    void withdraw(double amount) throws InsufficientBalanceException {

        if (amount > balance) {
            throw new InsufficientBalanceException(
                "Insufficient balance"
            );
        }

        balance -= amount;
    }
}

The method declaration:

throws InsufficientBalanceException

declares the possible exception.

The statement:

throw new InsufficientBalanceException(...)

creates and throws the exception.


Important Rules for throw

Remember these rules:

  1. throw is used to explicitly throw an exception.
  2. It must be followed by an exception object.
  3. The object must be an instance of Throwable or one of its subclasses.
  4. A checked exception thrown with throw must be handled or declared.
  5. Unchecked exceptions do not have to be declared.
  6. A throw statement transfers control away from the normal execution path.

Example:

throw new Exception("Something went wrong");

Important Rules for throws

Important rules for throws include:

  1. throws is used in a method or constructor declaration.
  2. It is followed by one or more exception types.
  3. Multiple exceptions are separated by commas.
  4. It is especially important for checked exceptions.
  5. It does not actually throw an exception by itself.
  6. It tells the caller that the method may propagate the specified exceptions.

Example:

void readFile() throws IOException {
}

Common Mistakes

Mistake 1: Thinking throws Handles the Exception

This is incorrect:

void process() throws IOException {
}

throws does not handle the exception. It only declares it.

The caller may need to handle the exception:

try {
    process();
} catch (IOException e) {
    System.out.println(e.getMessage());
}

Mistake 2: Using throw Without an Exception Object

Incorrect:

throw IOException;

Correct:

throw new IOException();

throw requires an exception object.


Mistake 3: Confusing Exception Type with Exception Object

Consider:

throw new IOException();

IOException is the exception type, while:

new IOException()

creates the exception object.

The throw statement throws the object.


Mistake 4: Declaring Unnecessary Checked Exceptions

Avoid adding broad or unnecessary checked exceptions to every method.

For example:

void calculate() throws Exception {
}

If the method does not actually need to propagate a checked exception, declaring Exception can make the API less precise.

Prefer specific exception types when declaration is necessary:

void readFile() throws IOException {
}

throw and throws Interview Question

Question

What is the difference between throw and throws in Java?

Answer

throw is used to explicitly throw a specific exception object from a method or block of code.

throw new IllegalArgumentException("Invalid value");

throws is used in a method declaration to specify that the method may propagate one or more exceptions to its caller.

void readFile() throws IOException {
}

In short:

throw  → actually throws an exception
throws → declares possible exceptions

Quick Comparison

throw throws
Used to explicitly throw an exception Used to declare possible exceptions
Used inside method/block Used in method/constructor declaration
Followed by an exception object Followed by exception class names
Throws one exception object per statement Can declare multiple exception types
Can be used with checked and unchecked exceptions Mainly relevant to checked exceptions
Transfers control to exception handling Passes responsibility to the caller

Key Points to Remember

  • throw explicitly throws an exception.
  • throws declares exceptions in a method signature.
  • throw is followed by an exception object.
  • throws is followed by exception class names.
  • A method can declare multiple exceptions using throws.
  • Checked exceptions must be handled or declared.
  • Unchecked exceptions do not have to be declared.
  • throw and throws are frequently used together.
  • try-catch is used to handle exceptions.
  • throws does not handle an exception; it communicates possible exception propagation.

Conclusion

Java provides throw and throws to give developers control over exception generation and propagation.

Use throw when your code needs to explicitly generate an exception:

throw new IllegalArgumentException("Invalid input");

Use throws when a method needs to declare that it may propagate an exception:

void readFile() throws IOException {
}

A clear understanding of throw, throws, and try-catch is essential for writing robust Java applications and is also a common topic in Java interviews.

Related

Found a problem on this page, or something that could be clearer?

Goes straight to the author. Not published anywhere.