how to use throws in handling Exceptions

As briefed in difference between Checked and Unchecked Exception, unchecked exceptions may or may not be handled. But, be aware that all Checked Exceptions either need to be handled using try and catch blocks or need to be further thrown using throws keyword. However it is responsibility of invokers of the method(which throws Exception) to handle it with try catch blocks, or further throw using throws keyword.

throws keyword need to be used along with method declaration, it just indicates that the method may throw an Exception, and invokers of the method need to either handle it or further throws it.

Also note that multiple Exceptions separated with comma, can be used with throws keyword. For eg

public void show() throws NullPointerException, Exception
{
//..statements
}

This feature, helps third party framework to throw an Exception, and let application developers to handle it appropriately.

Below is an example of throws keyword.


class TDemo1{
	public void met1() throws Exception
	{
	if(true)
	{
		throw new Exception("Some Exception");
	}
	}
}

class TDemo2{
	public void met2() throws Exception,NullPointerException
	{

	TDemo1 td = new TDemo1();
		
	td.met1();
	}
}

public class ThrowsDemo {
	public static void main(String args[]) throws Exception
	{
	try{
	TDemo2 td2 = new TDemo2();
	td2.met2();
		
	}catch(Exception e)
	{
		
	e.printStackTrace();
	//printsline number, class name, file name where the exception has occurred
	//and the methods thru which exception has been propogated, until caught
	throw e;//further rethrowing the exception
	}
	finally{
	System.out.println("dsdsfds");
	}
		
	}
}

You may also like to read:
Create user defined Exception
How to create Unchecked Exception
List of exceptions in java.lang package