In this tutorial, we will illustrate how to throw an exception in java. We use throw statement to throw an exception or simply use the throw keyword with an object reference to throw an exception. A single argument is required by the throw statement i.e. a throwable object. As mentioned earlier Throwable objects are instances of any subclass of the Throwable class. In the example below we show how to throw an exception. Here we are trying to divide a number by zero so we have thrown an exception here as "throw new MyException("can't be divided by zero");"

Java Code: Program to throw exception

class MyException extends Exception {

    public MyException(String msg) {

public class Test {

    static int divide(int first, int second) throws MyException {
        if (second == 0) {
            throw new MyException("can't be divided by zero");
        return first / second;

    public static void main(String[] args) {
        try {
            System.out.println(divide(4, 0));
        } catch (MyException exc) {
Output of program:

How can we throw exception in java?-output.jpg
Figure: Output showing exception thrown