温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java Throws如何抛出异常

发布时间:2026-07-26 16:35:00 来源:亿速云 阅读:83 作者:小樊 栏目:编程语言

在 Java 中,抛出异常通常使用 throw 关键字(不是 throwsthrows 只是声明)。下面分情况说明。


一、使用 throw 抛出异常(手动抛异常)

基本语法

throw new 异常类型("异常信息");

示例

public class Demo {
    public static void main(String[] args) {
        int age = -1;
        if (age < 0) {
            throw new IllegalArgumentException("年龄不能为负数");
        }
    }
}

运行结果:

Exception in thread "main" java.lang.IllegalArgumentException: 年龄不能为负数

二、throw vs throws 的区别

关键字 作用 使用位置
throw 真正抛出异常对象 方法体内
throws 声明方法可能抛出的异常 方法签名上

三、throws 声明异常(不处理,交给调用者)

示例

public class Demo {

    public static void test() throws Exception {
        throw new Exception("发生错误");
    }

    public static void main(String[] args) throws Exception {
        test();
    }
}

说明:

  • test() 方法内部抛出了异常
  • 使用 throws Exception 声明
  • main 方法要么继续 throws,要么 try-catch

四、受检异常 vs 运行时异常

1️⃣ 运行时异常(RuntimeException)

不需要 throws 声明

public static void test() {
    throw new RuntimeException("运行时异常");
}

常见运行时异常:

  • NullPointerException
  • IndexOutOfBoundsException
  • IllegalArgumentException

2️⃣ 受检异常(Checked Exception)

必须处理或声明

public static void readFile() throws IOException {
    throw new IOException("文件读取失败");
}

五、自定义异常并抛出

自定义异常类

class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

抛出自定义异常

public class Demo {
    public static void check(int num) throws MyException {
        if (num < 0) {
            throw new MyException("数字不能为负数");
        }
    }

    public static void main(String[] args) throws MyException {
        check(-1);
    }
}

六、总结一句话

抛出异常用 throw
声明异常用 throws
运行时异常可不用声明
受检异常必须处理或声明

如果你愿意,我也可以帮你画一张 异常抛出流程图 或结合 面试常问点 讲。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI