在 Java 中,throws 用于声明方法可能抛出的异常,告诉调用者“这个方法可能会出这些错,你要处理”。
修饰符 返回值类型 方法名(参数列表) throws 异常类型1, 异常类型2 {
// 方法体
}
public void readFile(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
}
| 关键字 | 作用 |
|---|---|
throws |
声明方法可能抛出的异常 |
throw |
真正抛出一个异常对象 |
// throws:声明
public void test() throws Exception {
// throw:抛出
throw new Exception("出错了");
}
Java 要求必须处理或声明:
public void save() throws SQLException {
// 数据库操作
}
调用时必须:
try {
obj.save();
} catch (SQLException e) {
e.printStackTrace();
}
或继续 throws
public void process() throws IOException, SQLException {
}
public void method() throws Exception {
}
✅ 可以覆盖 IOException、RuntimeException 等子类
public static void main(String[] args) throws Exception {
int a = 1 / 0;
}
⚠️ 程序直接终止,不推荐生产代码这样写
❌ throws 不能用于:
✅ 适合:
如果你愿意,我可以:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。