How can Java actively throw an exception?

Java allows you to actively throw exceptions using the throw keyword. Here is an example code:

public class Main {
    public static void main(String[] args) {
        try {
            // 主动抛出异常
            throw new Exception("这是一个自定义异常");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

In the example above, we used the throw keyword to throw an exception of type Exception, and caught and outputted the exception information in the catch block. You can throw different types of exceptions as needed, such as NullPointerException, IllegalArgumentException, and so on.

bannerAds