Monday, 15 September 2014

Throw Keyword , Throws Keyword and Difference between Throw and Throws

Throw keyword:


Throw keyword is used to throw an exception explicitly.

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

Throw Example in Java :


import java.io.*;
public class className
{
   public void deposit(double amount) throws RemoteException
   {
      // Method implementation
      throw new RemoteException();
   }
   //Remainder of class definition
}

Throws Keyword in java :



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.

Like if a method does not want or capable to handle the exception with throws keyword itself , it can use throws keyword in its signature so what will happen that the method which is calling that method will have code handle that exception .
This can be understand with the help of an example below:



Throws Example in Java :


class DemoThrowsException {
    public void readFile(String file) throws FileNotFoundException {
        //..code
    }
    void useReadFile (String name) {              
        try {                                      
            readFile(name);                        
        }                                          
        catch (FileNotFoundException e) {          
            //code                                 
        }                                          
    }
}

 This is a simple example of using throws keyword .
In this example readFile method is not handling the FileNotFoundException ,so it throws the exception 
which will be handled by useReadFile method with try catch block which is internally calling readFile method .

Difference between throw and throws in Java :


Throws
Throw
Throws clause in used to declare an exception throw keyword is used to throw an exception explicitly.

Throws is followed by exception class names throw is followed by an instance variable
Throws clause is used in method declaration (signature).

throw is used inside method body to invoke an exception
Using throws you can declare multiple exceptions Using Throw keyword in java you cannot throw more than one exception

User Defined Exception in Java:


User defined exceptions in java are also known as Custom exceptions. Most of the times when we are developing an application in java, we often feel a need to create and throw our own exceptions.

  • User defined exception needs to inherit (extends) Exception class in order to act as an exception.
  • throw keyword is used to throw such exceptions.

No comments:

Post a Comment