关于异常

1.RuntimeException,也就是运行时异常,表示你的代码本身存在BUG,比如你提到的ArrayIndexOutOfBoundsException,数组下标越界,这个属于代码有问题,数组定义的长度不够实际使用,不处理肯定会报错,如果你操作某个模块发现能正常运行,那只是因为代码还没跑到这个错误的地方而已。。控制台一旦报RuntimeException,就必须要处理。。没有例外的。而且,处理RuntimeException,不是try-catch能解决的。。try-catch在这里使用毫无意义。程序运行到此处终止
(RuntimeException抛出后不作处理后面程序肯定停止执行。但try catch可以捕获到异常,但没什么用)
2.不是RuntimeException,就是编译时异常,异常只有这两种了。比如你在处理文件流时的I/O问题,就属于编译时异常。这个时候用thr{}catch 来捕获或者 throws即可。程序继续运行

3.error,eclipse代码里出现红叉叉。
Unchecked Exception: 
a. 指的是程序的瑕疵或逻辑错误,并且在运行时无法恢复。 
b. 包括Error与RuntimeException及其子类,如:OutOfMemoryError, UndeclaredThrowableException, IllegalArgumentException, IllegalMonitorStateException, NullPointerException, IllegalStateException, IndexOutOfBoundsException等。 
c. 语法上不需要声明抛出异常。就算捕获了也没用 

Checked Exception: 
a. 代表程序不能直接控制的无效外界情况(如用户输入,数据库问题,网络异常,文件丢失等) 
b. 除了Error和RuntimeException及其子类之外,如:ClassNotFoundException, NamingException, ServletException, SQLException, IOException等。 
c. 需要try catch处理或throws声明抛出异常。 
 
 Java代码  
public class TestException {  
    public void first() throws GenericException {  
        throw new GenericException("Generic exception"); // Checked Exception需要显式声明抛出异常或者try catch处理  
    }  
     
    public void second(String msg) {  
        if (msg == null)  
            throw new NullPointerException("Msg is null"); // Unchecked Exception语法上不需要处理  
    }  
     
    public void third() throws GenericException {  
        first(); // 调用有Checked Exception抛出的方法也需要try catch或声明抛出异常  
    }  
 
    public static void main(String[] args) {  
        TestException test = new TestException();  
        try {  
            test.first();  
        } catch (GenericException e) {  
            e.printStackTrace();  
        }  
         
        test.second(null);  
    }  
}
原文地址:https://www.cnblogs.com/wangsong/p/4796410.html