Java throws Keyword

The throws keyword in Java is used in method signatures to declare that a method can throw one or more exceptions. This informs the callers of the method that they need to handle or propagate these exceptions.

Table of Contents

  1. Introduction
  2. throws Keyword Syntax
  3. Understanding throws
  4. Examples
    • Declaring a Method with Throws
    • Handling Multiple Exceptions
    • Using Throws with Custom Exceptions
  5. Real-World Use Case
  6. Conclusion

Introduction

In Java, exceptions can be broadly categorized into checked exceptions and unchecked exceptions. Checked exceptions must be either caught or declared in the method signature using the throws keyword. The throws keyword helps in propagating exceptions up the call stack, ensuring that they are handled appropriately.

throws Keyword Syntax

The syntax for using the throws keyword in a method signature is as follows:

returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {
    // method body
}

Example:

public void readFile(String fileName) throws IOException {
    // method body
}

Understanding throws

Key Points:

  • Exception Declaration: The throws keyword is used to declare exceptions that a method can throw.
  • Propagation: It allows the propagation of exceptions up the call stack, informing the caller to handle them.
  • Checked Exceptions: Primarily used for checked exceptions, which are checked at compile-time.

Examples

Declaring a Method with Throws

A method that declares an IOException using the throws keyword.

Example

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            readFile("test.txt");
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }

    public static void readFile(String fileName) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
}

Output:

Contents of the file (if exists) or error message

Handling Multiple Exceptions

A method that declares multiple exceptions using the throws keyword.

Example

import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            processFile("test.txt");
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO error: " + e.getMessage());
        }
    }

    public static void processFile(String fileName) throws FileNotFoundException, IOException {
        if (fileName == null) {
            throw new FileNotFoundException("File name cannot be null");
        }
        readFile(fileName);
    }

    public static void readFile(String fileName) throws IOException {
        // Method body (omitted for brevity)
    }
}

Output:

File not found: test.txt (if file is not found) or IO error message

Using Throws with Custom Exceptions

Declaring a method that throws a custom exception.

Example

class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            checkAge(15);
        } catch (InvalidAgeException e) {
            System.out.println("Caught an exception: " + e.getMessage());
        }
    }

    public static void checkAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be at least 18");
        }
        System.out.println("Age is valid");
    }
}

Output:

Caught an exception: Age must be at least 18

Real-World Use Case

Network Operations

In real-world applications, network operations often involve methods that can throw multiple exceptions, such as IOException and UnknownHostException. Using the throws keyword, these exceptions can be declared and handled appropriately.

Example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    public static void main(String[] args) {
        try {
            fetchDataFromUrl("http://example.com");
        } catch (MalformedURLException e) {
            System.out.println("Invalid URL: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO error: " + e.getMessage());
        }
    }

    public static void fetchDataFromUrl(String urlString) throws MalformedURLException, IOException {
        URL url = new URL(urlString);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        }
        in.close();
    }
}

Output:

Contents of the URL (if accessible) or error message

Conclusion

The throws keyword in Java is a powerful tool for exception handling, allowing methods to declare that they can throw specific exceptions. This ensures that exceptions are properly propagated up the call stack and handled by the calling methods. Understanding and using the throws keyword effectively is crucial for writing robust and maintainable Java applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top