Thursday, September 5, 2013

Difference between throws and throw ?


throws:

         If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.



throw:

        You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.

       To throw a custom exception , first we need to write a class  which extends one of the child class of Exception class or we can extend Exception class. And we can directly create an object to it and then thow inside a method where we need to throw it using 'throw' keyword.

for example:

    class AuthenticationException extends Exception. and we want to throw custom exception ,

use ' throw new AuthenticationException(); '

and here we can write parametrized constructor also.


So throw keyword is to throw library exceptions, and throw keyword is used to throw custom exceptions.


No comments:

Post a Comment