×
☰ See All Chapters

Java throw and throws

throw

The throw keyword is used to explicitly throw an exception. When one method calls another method (Either main method invoking other methods or other method invoking some other method) exception object is thrown to the caller method. Execution stops immediately after the throw statement and any subsequent statements are not executed. We can throw either checked or unchecked exception (subclasses of class Throwable). The throw keyword is mainly used to throw custom exception (generally).

Example of throw keyword

In this example, we have created the validate method that takes integer value as a parameter. This value is treated as age of a person. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.

java-throw-and-throws-0
 

Throwing same exception which is caught is known as Rethrowing an exception.

catch (WhateverException e) {

    throw e;

}

throws

In the above program of voting we want exception to occur mandatorily if age is below 18, otherwise any person with age below 18 can vote.  In the program we used ArithmeticException which is unchecked exception. But if any checked exception is used the program will not compile at all. So in order to compile the program and to arise checked exception during run time we use throws keyword to declare exception.

If I try to withdraw more money than I have in my checking account, exception should occur and should inform me that I am trying to overdraft. If exception doesn’t occur and fails to stop me from ignoring my overdraft then i can just go right on spending more money and then plead ignorance when my overdraft statement comes in the mail. I can tell the bank that I didn’t check the return value of the withdraw() method. In this case if checked exception is used then program will not compile at all. So in order to compile the program and to arise checked exception during run time we use throws keyword to declare exception.

When do you handle an exception and when do you declare an exception?

The answer is based on design decisions. Do you want a method to deal with a problem, or do you want the problem to be passed on to the caller of the method?

Suppose that I walk into my bank and make a deposit (by invoking a deposit() method), but the teller is having problems with his computer. That should not be my problem. In this case, the deposit() method should handle this exception and fix the problem without notifying me, the caller of the method. If I am in the middle of a deposit and the bank’s computer system fails, that might be my problem. In that case, I want to be informed that my deposit did not successfully go through. The deposit() method can tell me that the transaction was unsuccessful by throwing an exception back to me.

Syntax of throws keyword:

void methodName() throws exceptionClassName {  

        ...  

}

Example for throws

class Excep13 {

        void validate(int age) throws IOException {

                if (age < 18)

                        throw new IOException("not valid");

                else

                        System.out.println("welcome to vote");

        }

}

 

class ExceptionHandling {

        public static void main(String args[]) throws IOException {

                Excep13 obj = new Excep13();

                obj.validate(13);

                System.out.println("rest of the code...");

        }

}

Output:

(If age greater than 18)

welcome to vote                                            

rest of the code...

(If age less than 18)

Exception in thread "main" java.io.IOException: not valid

        at com.manum.hassan.Excep13.validate(ExceptionHandling.java:140)

        at com.manum.hassan.ExceptionHandling.main(ExceptionHandling.java:148)

 

Which exception should we declare?

We should declare only checked exception, because:

  • Unchecked Exception: under your control so correct your code.  

  • Error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError. 

Note: Generally we declare only checked exception, but declaring unchecked exception will not give any compilation error.

What is the advantage of throws keyword?

Checked Exception can be propagated (forwarded in call stack).

import java.io.IOException;

 

class ExceptionHandling {

        void method3() throws IOException {

                throw new IOException("device error");// checked exception

        }

 

        void method2() throws IOException {

                method3();

        }

 

        void method1() {

                try {

                        method2();

                } catch (IOException exp) {

                        System.out.println("exception handled");

                }

 

        }

 

        public static void main(String args[]) {

                ExceptionHandling obj = new ExceptionHandling();

                obj.method1();

                System.out.println("normal flow...");

        }

}

 

Output:

exception handled

normal flow...

In the above program following sequence happens

  1. main method is a caller of method1() 

  2. method1() is a caller of method2() 

  3. method2() is a caller of method3() 

  4. method3() throws exception to caller, method2() 

  5. method2() throws exception to caller, method1() 

  6. method1() handles exception using try catch  

 

java-throw-and-throws-1
 

Difference between throw and throws

throw

throws

throw is used to explicitly throw an exception.

throws is used to declare an exception.

Syntax:

throw <instance of any exception class>;

 

Syntax:

<method signature> throws <exception class name>  , <exception class name> ….

You can throw only one exception.

You can declare multiple exceptions.

 


All Chapters
Author