throw throws in Java

throw throws in Java

throw in Java

We can create an exception object explicitly and we can hand over this exception object to JVM manually by using the throw keyword.

The main objective of the throw keyword in Java is to hand over our created exception object to the JVM manually.

In the following given programs output will be the same.

Program 1

public class Throw {
    public static void main(String[] args) {
        System.out.println(10/0);
    }
}

In this program main method is responsible to create an Exception object and handing over that object to JVM.

Program 2

public class Throw {
    public static void main(String[] args) {
        throw new ArithmeticException("/ by zero");
    }
}

In this program, the programer created an Exception object and handover that object to JVM.

Note-

The best use of the throw keyword is for a customized exception or user-defined exception.

  • In Java after the throw statement we are not allowed to write any other statement directly otherwise we will get compile time error-“java: unreachable statement”.
public class Throw {
    public static void main(String[] args) {
        throw new ArithmeticException("/ by zero");
        System.out.println("throw keyword in Java");
    }
}

  • We can use the throw keyword only for throwable type. If we use the throw keyword with a normal Java object then we will get compile time error-“java: incompatible types: Throw cannot be converted to java.lang.Throwable”.
public class Throw {
    public static void main(String[] args) {
        throw new Throw();
    }
}

Throws in Java

We can use the throws keyword to transfer the responsibility of exception handling to the caller method (caller method can be a method or JVM) after that caller method is responsible for handling that exception.

Throws keyword required only for checked exceptions. for unchecked exceptions, there is no use and no impact of the throws keyword. uses of the throws keyword don’t prevent an abnormal termination of the Java program.

public class Throw {
    public static void main(String[] args) throws InterruptedException {

    }
    public static void method()throws InterruptedException{
     method2();
    }
    public static void method2() throws InterruptedException{
        Thread.sleep(10000);
    }
}

In the above Java program if we rename at least one throws statement then the code will not compile.

Note-

It is recommended to use the try-catch block over the throws keyword.

Similar Java Tutorials

5 thoughts on “throw throws in Java”

Leave a Comment