throws用来声明某一个方法可能抛出的异常,这个异常可以是系统定义的,也可以是自己定义的。
调用throws修饰的方法,必须要对其做异常处理,或者将异常声明抛出(使用throws)。
语法:
import java.io.*;
public class classname
{
public void deposit(double amount) throws remoteexception
// method implementation
}
//remainder of class definition
一个方法可以声明它抛出多个异常,在这种情况下,异常都是在以逗号分割的形式声明的。
public void withdraw(double amount) throws remoteexception,
insufficientfundsexception
例子:
public class exceptiontest{
public static void main(string args[]) throws ioexception, nullpointerexception{
file = new fileinputstream(filename);
x = (byte) file.read();
这将产生以下结果:
at java.io.fileinputstream.open(native method)
异常被抛出,中断执行,并打印了堆栈信息。
使用throw关键字可以抛出一个异常对象。
另外,如果一个方法不处理异常,则该方法必须使用throws关键字声明它。
throw new remoteexception();
public void main(string[] args) throws exception
throw new exception("异常");
exception in thread "main" java.lang.exception: 异常
at com.test.test.main(test.java:37)
异常被抛出,并打印了堆栈信息。
throws是用来声明一个方法可能抛出的所有异常信息。
throw则是指抛出的一个具体的异常对象。
原文地址:http://blog.csdn.net/ooppookid/article/details/51100373