Saturday , February 23 2019
Home / Java / Difference between throw and throws in Java

Difference between throw and throws in Java

There are many differences between throw and throws keywords. A list of differences between throw and throws are given below:

1) You can declare multiple exception thrown by method in throws keyword by separating them in common e.g. throws IOException, ArrayIndexBoundException etc, while you can only throw one instance of exception using throw keyword e.g. throw new IOException(“not able to open connection”).

 2) throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method signature a method suggesting its caller to prepare for Exception declared in throws clause, specially in case of checked Exception and provide sufficient handling of them. On the other hand throw keyword transfer control of execution to caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in below example:

private static boolean shutdown() {
        throw new UnsupportedOperationException(“Not yet implemented”);

as in below method shutdown should return boolean but having throw in place compiler understand that this method will always throw exception .

3) throws keyword cannot be used anywhere exception method signature while throw keyword can be used inside method or static initializer block provided sufficient exception handling as shown in example.

        try {
            throw new Exception(“Not able to initialized”);
        } catch (Exception ex) {
            Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex);

worth remembering is that static initializer block should complete normally.

4) throw keyword can also be used to break a switch statement without using break keyword as shown in below example:

int number = 5;
            case 1:
                throw new RuntimeException(“Exception number 1″);
            case 2:
                throw new RuntimeException(“Exception number 2″);

About admin

Check Also

Internal Working of HashMap in Java

In this article, we will see how hashmap’s get and put method works internally. What ...

Leave a Reply