throws in java

Previous
Next

throws:

  • ‘throws’ is a keyword.
  • It is used to specify that a method raises exception from its definition.
  • It is useful to pass the exertion handling process to method calling area when we don’t handle exception.
  • Default exception handler handles in case if we don’t handle the exception in any one level.
import java.io.*;
class FileHandle 
{
	public static void main(String[] args) throws FileNotFoundException
	{
		FileInputStream fis = new FileInputStream("g:/input.txt");
		System.out.println("File opened....");
	}
}

“throws” is giving information that, we need to handle exception while calling the function.

class CustomException extends Exception
{
	CustomException(String name)
	{
		super(name);
	}
}
class Test
{
	static void func() throws CustomException
	{
		CustomException err = new CustomException("Error-Name");
		throw err;
	}
}
class ThrowException 
{
	public static void main(String args[])
	{
		try
		{
			Test.func();  // calling
		}
		catch (CustomException e)
		{
			System.out.println("Exception : " + e.getMessage());
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form