Java throw and throws Keywords

Introduction

The throw and throws keywords in Java are used to handle exceptions. They play a crucial role in defining how exceptions are propagated and handled in Java programs. Understanding these keywords is essential for writing robust and fault-tolerant code.

Table of Contents

  1. What is the throw Keyword?
  2. What is the throws Keyword?
  3. Difference Between throw and throws
  4. Using the throw Keyword
  5. Using the throws Keyword
  6. Creating Custom Exceptions
  7. Real-World Analogy
  8. Example: Comprehensive Usage of throw and throws
  9. Conclusion

1. What is the throw Keyword?

The throw keyword is used to explicitly throw an exception in Java. When an exception is thrown using the throw keyword, the normal flow of the program is disrupted, and the control is transferred to the nearest enclosing catch block that can handle the thrown exception.

Syntax:

throw new ExceptionType("Error message");

2. What is the throws Keyword?

The throws keyword is used in a method signature to declare that the method might throw one or more exceptions. It informs the caller of the method that it should be prepared to handle these exceptions.

Syntax:

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

3. Difference Between throw and throws

Feature throw throws
Purpose Used to explicitly throw an exception Used to declare exceptions that might be thrown
Location Inside a method In the method signature
Number of Exceptions Can throw only one exception at a time Can declare multiple exceptions
Used for Throwing exceptions Informing the caller about potential exceptions

Example: Throwing a Checked Exception

public class ThrowExample {
    public static void main(String[] args) {
        try {
            validateAge(15);
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }

    static void validateAge(int age) throws Exception {
        if (age < 18) {
            throw new Exception("Age must be at least 18.");
        } else {
            System.out.println("Access granted.");
        }
    }
}

Output:

Exception caught: Age must be at least 18.

Example: Throwing an Unchecked Exception

public class ThrowUncheckedExample {
    public static void main(String[] args) {
        try {
            divide(10, 0);
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }

    static void divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Division by zero is not allowed.");
        } else {
            System.out.println("Result: " + (a / b));
        }
    }
}

Output:

Exception caught: Division by zero is not allowed.

5. Using the throws Keyword

The throws keyword is used to declare that a method might throw one or more exceptions. It is often used with methods that perform operations that might fail, such as file I/O or network communication.

Example:

import java.io.*;

public class ThrowsExample {
    public static void main(String[] args) {
        try {
            readFile("example.txt");
        } catch (IOException e) {
            System.out.println("IOException caught: " + e.getMessage());
        }
    }

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

Output:

IOException caught: example.txt (No such file or directory)

6. Creating Custom Exceptions

You can create custom exceptions by extending the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).

Example: Custom Checked Exception

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

    static void validateAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be at least 18.");
        } else {
            System.out.println("Access granted.");
        }
    }
}

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

Output:

Caught custom exception: Age must be at least 18.

7. Real-World Analogy

Consider a scenario where you are submitting a form:

  • Throw: You encounter an error and explicitly report it (e.g., "Age must be at least 18").
  • Throws: The form specifies the possible errors that might occur (e.g., "This form might throw an invalid age error").

8. Example: Comprehensive Usage of throw and throws

Example:

import java.io.*;

public class ComprehensiveThrowThrowsExample {
    public static void main(String[] args) {
        try {
            checkFile("example.txt");
        } catch (CustomFileNotFoundException | IOException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }

    static void checkFile(String fileName) throws CustomFileNotFoundException, IOException {
        File file = new File(fileName);
        if (!file.exists()) {
            throw new CustomFileNotFoundException("File not found: " + fileName);
        }
        FileReader fileReader = new FileReader(file);
        BufferedReader reader = new BufferedReader(fileReader);
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
}

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

Output:

Exception caught: File not found: example.txt

9. Conclusion

The throw and throws keywords in Java are essential for handling exceptions. The throw keyword is used to explicitly throw an exception, while the throws keyword is used to declare that a method might throw one or more exceptions. Understanding how to use these keywords effectively allows you to write robust and fault-tolerant Java programs. Custom exceptions can be created to handle specific scenarios, making your code more readable and maintainable.

Leave a Comment

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

Scroll to Top