要点Java15 异常

Tutorial

当一个错误发生时,程序就会抛出异常. 异常列表可以参考下面的链接http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html.

异常由 try/catch 语句处理. 可能抛出异常的所有代码都必须遵循Catch或指定的要求. 按照这个要求, 这段代码必须包含在try语句块中. 如果由于某种原因,它不适合或不能使用try / catch语句,则必须指定所有异常的方法/函数可以使用 throws 关键字抛出

public void writeFile() throws IOException 

您也可以在代码中抛出一个新的异常::

throw new IllegalArgumentException("Number not above 0");
/* 将打印 
    Exception in thread "Main": java.lang.IllegalArgumentException: Number not above 0
*/

异常由 try/catch 语句处理, 这在前面已经学习:

try {
    System.out.println(arr[10]);
catch (ArrayIndexOutOfBoundsException ex) {
    System.out.println("Error in try block");
}

Exercise

写一个程序抛出一个异常 IllegalArgumentException if (n < 0). 必须描述写为 Error.

Tutorial Code

public class Main {
    public static void main(String[] args) {
        int n = -1;
    }
}

Expected Output

//需要写出相似的描述.
Exception at thread "main": java.lang.IllegalArgumentException: Error

Solution

public class Main {
    public static void main(String[] args) {
        int n = -1;
        if (n < 0) {
            throw new IllegalArgumentException("Error")
        }
    }
}


说明:该系列文章结合多家网站资料,以及国外教程翻译总结的相关要点,提供的简单自学材料 for my friends。
你也可以在github更新及获得更多信息:https://github.com/txidol/interactive-tutorials


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值