Java Exception handling using Java throw

w‮uttual.ww‬ri.com
Java Exception handling using Java throw

In Java, you can use the throw statement to throw an exception. The throw statement allows you to throw an exception manually, rather than having it thrown automatically by the Java runtime when an error occurs.

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

public class Main {
    public static void main(String[] args) {
        try {
            int x = 1;
            int y = 0;
            if (y == 0) {
                throw new ArithmeticException("Division by zero");
            }
            int z = x / y;
        } catch (ArithmeticException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

In this example, an ArithmeticException is thrown manually using the throw statement if the value of y is zero. The ArithmeticException is caught in the catch block and the exception's message is printed.

You can use the throw statement to throw any exception that you want, including a custom exception that you define yourself. Just use the throw statement followed by a new instance of the exception you want to throw.

Created Time:2017-11-03 15:57:10  Author:lautturi