Throws keyword in java

Throws

  • Throws is used to propagate the Exception.
  • You can write throws keyword at the time of method declaration.
  • You have handle that Exception at the time of calling that method.
  • Throws is class type it means after throws you have to write Exception class.
How to Propagate Exception in java using Throws ?

package exceptionHandling;


class Demo123
{

	void printnumber(int n,int m) throws InterruptedException 
	{
		
		for(;n<=m;n++)
		{
			System.out.println(n);
			Thread.sleep(1000);	
			
		}
	}
}


public class UseOfThrows
{
public static void main(String[] args) 
{

	System.out.println("****************************");
	
     Demo123 obj1=new Demo123();	
    
    	 
       try 
          {
	    obj1.printnumber(1, 5);
	  } 
     
     catch (InterruptedException e) 
	   {
		e.printStackTrace();
	   }
     
    
     
	System.out.println("*****************************");
  }

}

output:

****************************
1
2
3
4
5
*****************************

Leave a Reply