What is the difference between Throw and Throws in Java Exception Handling?

This one among most famous Java Interview Question.So what is the difference between Throw and Throws in Java Exception Handling? Lets first discuss about Java Exception and Exception Handling.

difference between Throw and Throws in Java Exception Handling

What is Java Exception ?


Java handle errors though a event called exception in Java. So whenever any error occur exception event create an object and this object is handed to run time system. Run time system get details of error like its information, type of error, states of program at the time of error.

What is Exception Handling ?


When Java run time system get exception object than it have its details as mention above. With help of these details it try to handle it and try to avoid failure of program if possible.


Throw and Throws in Java Exception Handling


Throw Clause :

When we want to throw an exception explicitly than throw keyword can be used. After using throw keyword instance variable come in code. Throw keyword used inside method.

example of Throw :


package Test;

/**
 *
 * @author Azure
 */
public class ThrowExample {
    
    
    
    public static void main(String arg[]) throws Exception
    {
        boolean check=true;  //Used true directly can be used some function
                            //which return false when something went wrong    
        if(!check)
        {
        throw new Exception("Something went wrong!!");
        }
        else
        {
            // Rest of code
        }
    } 

    
}



Throws Clause :

Throws keyword is used in method signature itself. Throw keyword is followed by exception class name.
If a method can cause exception and you are not aware when but you want to handle it anyway than use throws keyword with all possible exception declared in method signature.

Example of throws keyword :

public class ThrowsExample {
    
    
    
    public static void main(String arg[]) throws ArithmeticException, Exception
    {
        boolean check=true;  //Used true directly can be used some function
                            //which return false when something went wrong 
        
        int a=0;           
        int b=a/a;  /*This will cause Arithmetic Exception 
                    which will caught by ArithmeticException instance 
                    called in throws keyword in method declaration*/
        
              
        if(!check)
        {
        throw new Exception("Something went wrong!!");
        }
        else
        {
            // Rest of code
        }
    } 

    
}


Hope this will help you to understand basics of throw and throws Exception handling in Java.


Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

0 comments:

Post a Comment