Java2all.com  

Throws





Share This Topic -

If a method is capable of causing an exception that it does not handle,

it must specify this behavior so that callers of the method can guard themselves against that exception.

You do this by including a throws clause in the method’s declaration. Basically it is used for IOException.

A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException,or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause.

If they are not, a compile-time error will result.

This is the general form of a method declaration that includes a throws clause:

type method-name(parameter-list) throws exception-list

{

// body of method

}

Here, exception-list is a comma-separated list of the exceptions that a method can throw.

Throw is used to actually throw the exception, whereas throws is declarative statement for the method. They are not interchangeable.

EX :

 class NewException extends Exception
{
	public String toS()
	{
		return "You are in NewException "; 
	}
}

class customexception
{
	public static void main(String args[])
	{
		try
		{
			doWork(3);
			doWork(2);
			doWork(1);
			doWork(0);
		}
		catch (NewException e)
		{
			System.out.println("Exception : " + e.toS());
		}
	}
	
	static void doWork(int value) throws NewException
	{
		if (value == 0)
		{
			throw new NewException();
		}
		else
		{
			System.out.println("****No Problem.****");
		}
	}
}

 
Output:
****No Problem.****
****No Problem.****
****No Problem.****
Exception : You are in NewException