一、throws
- throws 关键字将逗号分隔的 java.lang.Throwables 列表作为参数。
- 引发非 RuntimeException 异常的任何方法还必须在方法声明中使用 throws 修饰符来声明它引发的异常。
- 要在 try-catch 块中包含带 throws 子句的方法的调用,必须提供该方法的调用者。
- -示例-
import java.io.IOException; public class MyClass{ public method readFile(String filename) throws IOException,ClassCastException{ <statements> if (error){ throw new IOException("error reading file"); } } }
二、 throw
- throw 关键字用于引发异常。
- throw 语句将 java.lang.Throwable 作为参数。Throwable 在调用栈中向上传播,直到被适当的 catch 块捕获。
- -示例-
import java.io.IOException; public class MyClass{ public method readFile(String filename) throws IOException{ <statements> if (error){ throw new IOException("error reading file"); } } }
三、throws和throw的区别
- throws使用在函数上。throws后面跟的异常类,可以跟多个,用逗号隔开。
- throw使用在函数内。throw后跟的是异常对象。