Search code examples
javaexceptionthrowthrows

Throw keyword in Java


In Java, is the keyword (throw) only used for throwing exception that you've created. If not, can someone give an example of how it is used outside of your own made exceptions.


Solution

  • You can throw anything that extends Throwable

    void greet(String name) {
        if (name == null) {
            throw new IllegalArgumentException("Cannot greet null");
        }
        System.out.println("Hello, " + name);
    }