Java(异常)

  • 常见异常,例:
  1. ArraylndexOutOFBoundsException(数组下标越界)
  2. NullPointerException(空指针异常)
  3. ArithmeticException(算数异常)
  4. MissingResourceException(丢失资源)
  5. ClassNotFoundException(找不到类)

异常处理的五个关键字(try,catch,finally,throw,throws)

  • idea快捷键:选中一行代码,Ctrl+alt+t,自动生成try catch。
try,catch,finally示例:
public class userService{
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            System.out.println("ArithmeticException");//可以自己写异常,也可以用以下方法
            e.printStackTrace();//打印错误的栈信息
        } finally {
        }
        try {//监控区域
            System.out.println(a/b);
        }catch(Error e){//捕获错误

        }catch(Exception e){//捕获异常
            System.out.println("分母不能为零!");
        }catch(Throwable e){//最高级

        }finally {//善后工作,可以不写。如scanner后,可以释放scanner占用的空间
            System.out.println("finally");
        }
    }

}