Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Java throw vs throws: Mastering Exception Handling with Practical Examples

Java throw vs throws: Mastering Exception Handling with Practical Examples

This guide explains how to use Java’s throw and throws keywords for effective exception handling, illustrated with real‑world code samples.

In Java, exceptions fall into two categories:

For a deeper dive, see Java Exceptions.

Unchecked exceptions usually signal programming mistakes; they should be corrected rather than caught. Checked exceptions, on the other hand, represent conditions that callers must be aware of and handle.


Using the throws Keyword

The throws clause declares that a method may throw one or more exceptions, delegating the responsibility to callers. Its syntax is:

accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 { /* code */ }

You can list multiple exception types, separated by commas.


Example 1: Declaring a Checked Exception

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    // Code that may trigger IOException
    File newFile = new File("test.txt");
    FileInputStream stream = new FileInputStream(newFile);
  }

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

Output

java.io.FileNotFoundException: test.txt (No such file or directory)

If test.txt is missing, FileInputStream throws a FileNotFoundException, which is a subclass of IOException. Because findFile() declares throws IOException, the main() method must handle or propagate the exception.


Throwing Multiple Exceptions

You can declare several exception types in a single throws clause:

import java.io.*;
class Main {
  public static void findFile() throws NullPointerException, IOException, InvalidClassException {
    // Potentially throws NullPointerException
    …
    // Potentially throws IOException
    …
    // Potentially throws InvalidClassException
    …
  }

  public static void main(String[] args) {
    try {
      findFile();
    } catch (IOException e1) {
      System.out.println(e1.getMessage());
    } catch (InvalidClassException e2) {
      System.out.println(e2.getMessage());
    }
  }
}

Notice that NullPointerException is unchecked, so it need not be caught or declared by the caller.


When to Use throws vs. try...catch

Embedding try...catch in every method that might throw an exception can clutter code and obscure logic. Declaring throws keeps the method signature clean and allows higher‑level code to decide how to handle errors.


Using the throw Keyword

The throw statement explicitly throws an exception instance, transferring control to the nearest matching catch block or terminating the program if unhandled.

Syntax:

throw throwableObject;

Here, throwableObject is an instance of Throwable or one of its subclasses.


Example 2: Throwing an Unchecked Exception

class Main {
  public static void divideByZero() {
    throw new ArithmeticException("Trying to divide by 0");
  }

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

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
    at Main.divideByZero(Main.java:3)
    at Main.main(Main.java:7)
exit status 1

Since ArithmeticException is unchecked, catching it is optional.


Example 3: Throwing a Checked Exception

import java.io.*;
class Main {
  public static void findFile() throws IOException {
    throw new IOException("File not found");
  }

  public static void main(String[] args) {
    try {
      findFile();
      System.out.println("Rest of code in try block");
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

Output

File not found

Here, findFile() throws a checked IOException, so callers must either handle or declare it. The main() method demonstrates catching the exception, preventing the program from terminating.



Java

  1. Understanding Java: JDK, JRE, and JVM Explained
  2. Java Variables and Literals: A Comprehensive Guide
  3. Mastering Java While & Do‑While Loops: Step‑by‑Step Tutorial
  4. Java Classes and Objects: A Practical Guide
  5. Java Abstract Classes and Methods: A Comprehensive Guide
  6. Mastering Java Nested and Inner Classes: Types, Examples, and Best Practices
  7. Java Exceptions: Types, Hierarchy & Handling
  8. Mastering Multi‑Exception Handling in Java
  9. Master Java Autoboxing and Unboxing: Practical Examples and Best Practices
  10. Mastering Java Exceptions: Handling Unexpected Errors Gracefully