Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

difference between throw and throws

Status
Not open for further replies.

satellite03

IS-IT--Management
Dec 26, 2003
248
IN
hi, are these throw and throws are two different keywords in java?? if so, when throw is usued and when throws is usued?

any small code plz...
thanks
 
....in case of ioexception i have usued public static void main(String args[])throws IOException ..
 
Hope these examples clear it up for you :
Code:
public void myMethod() throws IOException {
    FileInputStream fis = new FileInputStream();
    fis.read();
}

OR

public void myMethod() throws CustomException {
  try {
    FileInputStream fis = new FileInputStream();
    fis.read();
  } catch (IOException ioe) {
      ioe.printStackTrace();

      throw new CustomException("Causgt an IOException but am throwing this CustomException instead");
  }
}
 
hi, i have come to conclusion that throw usued basically for user-defined exception.......
i tested
Code:
import java.lang.Exception;
class MyException extends Exception
{
	MyException (String message)
	{
		super(message);
	}
	
}

class TestMyException
{	public static void main(String args[])
	{  int x = 5,y = 1000;
		try
		{ float z =(float) x /(float)y ;
			if(z<0.01)
			{
				throw new MyException(&quot;number is too small&quot;);
			}
			
		}
		catch(MyException e)
		{ 
			System.out.println(&quot;caught my exception&quot;);
			System.out.println(e.getMessage() );
		}
		
		finally
		{
			System.out.println(&quot;I am always here&quot;);
		}
		
	}
	
}



and about throws ..it basically used in the function header and usues standard exception handler classes.

thanks
 
Yupp, that's the basic idea.

Anyway, you can throw any exception, not just user defined

Cheers.

Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top