The keyword throw can be used to actually throw an exception within your code.
For example...
public static void main(
String argv[])
{
int x = 7;
int y = 0;
int z = 0;
if (y == 0)
throw new ArithmeticException();
else
z = x/y;
}
The above code will throw an ArithmeticException at runtime.
The throws clause is used to indicate that a method throws an exception and that whoever calls it must handle the exception that it may throw (if its a checked exception).
For example, RandomAccessFile's constructor throws an IOException. This is evident in the constructor's declaration.
RandomAccessFile(String file, String mode) throws IOException
...that means that if you call the constructor, you must deal with the exception that the method "throws". If you don't, and the exception is a checked exception (not a subclass of RuntimeException), then it will cause a compile time error.
For example, the below code will not compile...
public static void main(String argv[])
{
RandomAccessFile r = new RandomAccessFile("io.txt","rw");
}
Whereas the following code will compile....
public static void main(String argv[])
{
try
{
RandomAccessFile r = new RandomAccessFile("io.txt","rw");
}
catch (IOException e)
{
System.out.println("Exception caught");
}
}
Hope that helped.
Jimmy Blakely
Sun Certified
Java Programmer
Travis County Certified Defensive Driver