Java throw and throws – Complete Guide with Examples


Learn the difference between throw and throws in Java, how to explicitly throw exceptions, declare exceptions in methods, and handle runtime and checked exceptions for robust programming.

throw and throws in Java – Complete Detailed Tutorial

Java provides throw and throws keywords to handle exceptions more effectively.

1. throw Keyword

  1. Used to explicitly throw an exception in Java
  2. Can throw checked or unchecked exceptions
  3. Syntax:

throw new ExceptionType("Error message");

Key Points:

  1. Used inside a method
  2. Terminates the current method execution
  3. Can throw only one exception at a time

Example – Using throw:


public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Age must be 18 or older");
} else {
System.out.println("Access granted");
}
}

public static void main(String[] args) {
checkAge(15);
}
}

Output:


Exception in thread "main" java.lang.ArithmeticException: Age must be 18 or older

2. throws Keyword

  1. Declares that a method may throw one or more exceptions
  2. Syntax:

returnType methodName() throws ExceptionType1, ExceptionType2 {
// code that may throw exception
}

Key Points:

  1. Used in method declaration
  2. Caller of the method must handle the exception
  3. Can declare multiple exceptions separated by comma

3. Example – Using throws


import java.io.*;

class Demo {
void readFile() throws IOException {
FileReader fr = new FileReader("test.txt");
fr.close();
}
}

public class Main {
public static void main(String[] args) {
Demo demo = new Demo();
try {
demo.readFile();
} catch (IOException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

Output (if file not found):


Exception caught: test.txt (No such file or directory)

4. Difference Between throw and throws

Featurethrowthrows
PurposeTo explicitly throw an exceptionTo declare exceptions a method may throw
UsageInside method bodyMethod signature
Can throwSingle exception at a timeMultiple exceptions separated by comma
TerminationImmediately terminates methodNot terminates method, just declares
Examplethrow new IOException();void read() throws IOException

5. Example – throw vs throws


import java.io.*;

class Test {
void method1() throws IOException {
throw new IOException("File error"); // throw keyword
}
}

public class Main {
public static void main(String[] args) {
Test t = new Test();
try {
t.method1(); // throws handled here
} catch (IOException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}

Output:


Caught exception: File error

6. Key Points

  1. throw: explicitly throw an exception inside method
  2. throws: declare possible exceptions in method signature
  3. Checked exceptions: must be handled or declared
  4. Unchecked exceptions: optional to handle
  5. Enables controlled exception handling