异常(Exception)

Error(错误)

错误不是异常,而是脱离程序员控制的问题。

Error类对象有由java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关

RuntineException (运行时异常)

  1. ArrayIndexOutOfBoundsException (数组下标越界)

  2. NullPointerException (空指针异常)

  3. ArithmeticException (算术异常)

  4. MissingResourceException (丢失资源)

  5. ClassNotFoundException (找不到类)等异常,这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理

这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这类异常的发生

Error和Exception的区别:

Error通常是灾难性的致命的错误,是程序无法控制和处理的,当出现这些异常时,Java虚拟机(JVM) - -般会选择终止线程; Exception通常情况下是可以被程序处理的,并且在程序中应该尽可能的去处理这些异常。

异常及其处理_代码编写

异常处理机制

五个关键字

try,catch,finally,throw,throws

public class Test {
    public static void main(String[] args) {
        int a=1;
        int b=0;
        
        //try,catch必须要有,finally可以不要
        try{//try监控区域   这里面的代码有异常就可以捕获的到
            System.out.println(a/b);
        }catch(ArithmeticException e) {//catch  捕获异常   ()中为异常类型,若上述代码中有这个异常,就执行catch中的代码
            System.out.println("程序出现异常,变量b不能为0");
        }finally{//处理善后工作,无论出不出现异常,都执行
            System.out.println("finally");
        }
    }
}
//可以写多个catch  从上到下,从小到大

快捷键:选中输出的内容+Ctrl+Alt+t 生成try/catch/finally

 public static void main(String[] args) {
        int a=1;
        int b=0;

        try {
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace();//打印错误的栈信息
        } finally {
        }
    }
}
抛出异常
public class Test {
    public static void main(String[] args) {

        new Test().test(1,0);

    }

    //假设这方法中,处理不了这个异常,方法上抛出异常
    public void test(int a,int b){
        if(b==0){//主动抛出异常   throw   throws
            throw new ArithmeticException();//主动抛出异常,一般在方法中
        }
        System.out.println(a/b);
    }
}