Throw an Exception in Java

Throw an Exception in java

To throw an exception in java we use the throw keyword that takes as argument an exception.

If no try{}catch is specified the program will stop running.

public class ThrowException {

    public static void main(String args[]) {
        // This throw NullPointerException
        String nullStr = null;
        if (nullStr == null) {
            throw new NullPointerException("Throw exception");
        }
        System.out.println(nullStr.toLowerCase());
    }
}