try, catch, throw , throws, finally

Java provides five keyword for Exception Handling :
  1. try
  2. catch
  3. finally
  4. throw
  5. throws
  • try-catch is a block of statements to try some commands and trap the runtime errors.
  • A try can have many catch statements.
  • finally is again a block to always execute some code irrespective of an exception. A try can have only one finally block at the bottom.

try{
	//statements
}
catch(classname referencename){
	//decision
}
catch(classname referencename){
	//decision
}
finally{
	//statements
}
    Note
  1. Even return statement cannot stop the finally block.
  2. If we use System.exit() method then finally will not execute
throw keyword is used to throw an object of some kind of class exception and
throws keyword is used to carry forward that exception object.
Example:
Create a class Number having a field as num. Create a blank constructor and initialize the num by -1.
Create another constructor to initialize the value of num. If a person tries to put the values below 1 then throw a message "Sorry! Number must be greater than 0".
Create a method factorial() which returns factorial of num. If no data get provided then throw another message "Sorry! No Data Provided".
Example 1:
public class Number 
{
    private int num;
    public Number()
    {
        num=-1;
    }
    public Number(int num) throws Exception
    {
        if(num<1) throw new Exception("Sorry! Number must be greater 
        	than 0");
        
        this.num=num;
    }
    public long factorial() throws Exception
    {
        if(num==-1)
            throw new Exception("Sorry! Not Data is provided");
        
        long f=1;
        for(int i=1;i<=num;i++)
            f=f*i;
        return f;
    }
}

class Test
{
    public static void main(String args[])
    {
       try
       {
            Number x=new Number(-6);
            System.out.println(x.factorial());
       }catch(Exception ex)
       {
           System.out.println(ex.getMessage());
       }
    }
}