Throw Keyword in Java

In Java, the throw keyword is used to explicitly throw an exception from a method or block of code. This keyword is used when the program encounters an exceptional condition that cannot be handled by the program, and the program needs to terminate abruptly.

When a throw statement is executed, it throws an object of a specific exception type. The thrown exception can be caught and handled by a try-catch block in the calling method or propagated up the call stack until it is caught and handled by a try-catch block or until it reaches the top of the call stack, where the JVM will terminate the program and print the stack trace of the exception.

Here's an example of how to use the throw keyword in Java:

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

    public class Example {
        public static void main(String[] args) {
            try {
                int num = -1;
                if (num < 0) {
                    throw new CustomException("Number cannot be negative");
                }
            } catch (CustomException e) {
                System.out.println(e.getMessage());
            }
        }
    }
                
            

In this example, we define a Custom Exception class, CustomException that extends the built-in Exception class. We then create a main() method that throws an instance of the CustomException class if the value of num is less than 0. The exception is caught and handled in the catch block by printing the message associated with the exception object.

Using the throw keyword is useful when we want to handle an exceptional condition in a specific way, rather than relying on the default behavior of the JVM. By explicitly throwing an exception, we can provide more detailed information about the exceptional condition and how to handle it.