Differences between throw and throws in java





In this post we will be discussing differences between throw and throws


Differences between throw and throws in java >



1
throw keyword is used to throw an exception explicitly.
throws keyword is used to declare an exception.
2
throw is used inside method.

Example >
static void m(){
   throw new FileNotFoundException();
}
throws is used in method declaration.

Example >
static void m() throws FileNotFoundException{
}
3
throw is always followed by instanceof Exception class.

Example >
throw new FileNotFoundException()
throws is always followed by name of Exception class.

Example >
throws FileNotFoundException
4
throw can be used to throw only one exception at time.

Example >
throw new FileNotFoundException()
throws can be used to throw multiple exception at time.

Example >
throws FileNotFoundException, NullPointerException

and many more...
5
throw cannot propagate exception to calling method.
throws can propagate exception to calling method.

Please see these programs to understand how exception is propagated to calling method.
Program 1 - Handling Exception by throwing it from m() method (using throws keyword) and handling it in try-catch block from where call to method m() was made.

Program 2 - Throwing Exception from m() method and then again throwing it from calling method [ i.e. main method]

Similarities between throw and throws in java >
Though there are not much similarities between two, but both are keywords in java.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */



RELATED LINKS>

eEdit
Must read for you :