您的位置:首页 > 编程语言 > Java开发

要点Java15 异常

2014-03-25 11:52 239 查看


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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: