Throw Keyword in Java | Exception Handling Mechanism

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. This mechanism is crucial for implementing custom error handling in your applications, allowing developers to generate exceptions when certain conditions are met.

Key Points on Throw Keyword:

Syntax of Throw Keyword:

Syntax Example

throw new ExceptionType("Error message");

Example of Throw Keyword in Java:

This example demonstrates throwing an exception when a user input is invalid.

Code Example

import java.util.Scanner;

public class ThrowExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a positive number: ");
        int number = scanner.nextInt();
        
        try {
            if (number < 0) {
                throw new IllegalArgumentException("Negative number provided: " + number);
            }
            System.out.println("You entered: " + number);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }
}

Output

Error: Negative number provided: -5

Detailed Explanation:

Additional Points on Throw Keyword in Java:

The throw keyword is an essential aspect of Java's exception handling mechanism, allowing for robust error management and enhancing the reliability of Java applications.