Throws keyword in Java

In Java, the throws keyword is used to declare the exceptions that can be thrown by a method. This keyword is used in the method signature to indicate that the method may throw one or more exceptions, which need to be caught and handled by the calling method or propagated up the call stack until they are caught and handled.

The throws keyword is followed by the name of the exception or a list of exceptions separated by commas. If a method throws an exception that is not declared in the throws clause, the compiler will generate an error.

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

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

        public static void doSomething() throws IllegalArgumentException {
            // code that may throw an IllegalArgumentException
        }
    }
                
            

In this example, we have a main() method that throws an instance of IllegalArgumentException 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.

We also have a doSomething() method that declares that it may throw an IllegalArgumentException by using the throws keyword. If the doSomething() method throws an IllegalArgumentException, the exception will be propagated up the call stack until it is caught and handled by a try-catch block.

The throws keyword is useful when we want to indicate the exceptions that can be thrown by a method and ensure that the calling method or the top-level caller handles the exception appropriately. It helps to provide more detailed information about the exceptional condition and how to handle it.