Throw Keyword Vs. Throws Clause

Java Syntax & Run time Errors, Java Exceptions, ArithmeticException, NumberException, NullPointerException and ArrayIndexOutOfBoundsException etc,Inserting Exception handling code in Java Programs.
Post Reply
ramya
Posts: 89
Joined: Fri Nov 23, 2018 2:55 am

Throw Keyword Vs. Throws Clause

Post by ramya » Wed Dec 05, 2018 9:23 am

What Is Throw Keyword & What Is Throws Clause?

manoj
Posts: 87
Joined: Fri Nov 23, 2018 5:29 am

Re: Throw Keyword Vs. Throws Clause

Post by manoj » Wed Dec 05, 2018 9:24 am

Throw Keyword :

It is possible for a Java program to throw an exception explicitly that is done using the throw statement.

The general form of throw is -

throw throwableObject;

We can get this throwableObject in 2 ways -

By using the Exception parameter of catch block.
Create a new one using the new operator.

try{
throw new NullPointerException();
}catch(NullPointerException nExp){
System.out.println("Exception caught in catch block of displayValue");
throw nExp;
}
}

Throws Clause :

If in a method we don't want to handle any exception but want to leave it to the calling method to handle any exception that is thrown by the called method, it is done using throws keyword.

Using throws a method can just declare the exception it may throw and callers of the method have to provide exception handling for those exceptions (or they can also declare them using throws).

General form of a method declaration that includes a throws clause

type method-name(parameter-list) throws exception-list

{
// body of method
}

Post Reply

Return to “Java Exception Handling”