异常的概念
Java语言中,将程序执行不正常的情况称为异常。
语法错误和逻辑错误不算。
异常分为两大类:
- Error错误,Java虚拟机无法解决的严重问题,程序会奔溃。JVM系统出错,资源耗尽,栈溢出等。
- Exception,其他因编程错误或偶然的外在因素导致的一般问题,可以使用针对性的代码进行处理。空指针访问,读不存在,网络终端等。Exception也分为两类:
- 运行时异常,需要避免
- 编译时异常,必须处理
异常体系图
常见的异常
-
NullPointerException空指针异常
-
public class NullPointerException_ { public static void main(String[] args) { String name = "hah"; System.out.println(name.length());//3 String sex = null; System.out.println(sex.length());//Exception in thread "main" java.lang.NullPointerException } }
-
-
ArithmeticException数学运算异常
-
public class Exception01 { public static void main(String[] args) { //int i = 10/0; //System.out.println(i); // Exception in thread "main" java.lang.ArithmeticException: / by zero //at Exception01.main(Exception01.java:3) //使用try-catch异常处理机制 //提高程序健壮性 //进行异常处理,如果出现异常,程序会继续执行 try { int i = 10/0; } catch (Exception e) { // e.printStackTrace(); System.out.println(e.getMessage());//输出异常信息 / by zero } } }
-
-
ArrayIndexOutOfBoundsExceprion数组下标越界异常
-
public class ArrayIndexOutOfBoundsExceprion_ { public static void main(String
-