Throws Keyword Simplified in Java



Throws keyword is used to indicate that a method may throw one or more exceptions that are defined in the method header or signature. For cases where the exception handling is mandatory for those cases the method must announce the throws clause in the definition.The caller of the method may choose to handle those exception or can throw again.So handling of these exception is optional.

Handling every exception is very tedious job and may hinder the coder's output. If we do not handle the exception in a try-catch block,we can  throw the exception to the calling method.If either of the two is not done compiler will throw an error. The idea behind enforcing this rule is that as a programmer ,we should aware that a piece of code be risky and throws some exception.
By throws keyword a designer of a method may throw any number of exceptions separated by comma(,).By throwing an exception , we can propagate and handle the exception is somewhere else in the code.

The syntax for throws is given as :

method(argumentList) throws ExecptionType1,ExceptionType2,....,ExceptionTypeN
{
}
 
like:

void processMyArray(int A[])throws NullPointerException,ArrayIndexOutOfBoundsException,ArrayStoreException
{
}
 
An Example:

public static void divide(int x,int y)throws Exception{
if(y==0)
throw new Exception("The divisor can not be Zero");
int z=x/y;
}
 
In the above code there is no try catch block to safeguard the potential risky code.Instead we throw an exception from here and the signature of the method says it can throw an Exception.In case if there is any Exception is created, the object will be propagated to the calling method.The calling method (may be main). The calling method should handle the exception.

public static void callerMethod()
{
try{
divide(10,0);
}
catch(Exception e)
{
}
}
 
The callerMethod , if does not handle the Exception may choose to throw again.

public static void callerMethod() throws Exception
{
divide(10,0);
}
 
In cases , where some statement in the body of a subroutine that can throw the exception by using throw statement(throw an exception directly),like our previous divide by zero example,or it could be a call to a method that can throw an exception.In both the cases,the exception must be handled.However it is good to handle the exception for any exception that is not subclass of error or RuntimeException. Exceptions that require mandatory handling generally represent conditions that are outside the control of the program.


Throws Keyword Simplified in Java Throws Keyword Simplified in Java Reviewed by Animesh Chatterjee on September 26, 2018 Rating: 5

No comments:

Powered by Blogger.