验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Java Throws如何抛出异常

阅读:220 来源:乙速云 作者:代码code

Java Throws如何抛出异常

在 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
运行时异常可不用声明
受检异常必须处理或声明

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

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>