目录
1、运行时异常 RuntimeException的子类都是运行时异常
索引越界异常IndexOutOfBoundsException
一、断言
1、功能
JDK1.4版本开始,增加了断言机制;
断言用来进行调试,不在生产环境中使用;
换言之,断言是为了帮助程序员在编程的过程中,尽快发现错误并进行修改,使得程序在生产环境中正常运行;
2、assert关键字表示
assert <布尔表达式> assert <布尔表达式> : <错误信息>
- 当布尔表达式的值是true时,忽略assert;
- 当布尔表达式的值是false时,发生AssertionError错误,程序中断;如果用第二种形式,同时显示错误信息;
3、idea开启断言
Edit Configurations
找到要执行的类,在VM options添加 -ea
public class Test1 {
public static void main(String[] args) {
int i=10;
assert i!=10:"断言错误!";
System.out.println("i = " + i);
}
}
/*
Exception in thread "main" java.lang.AssertionError: 断言错误!
at a07.Test1.main(Test1.java:6)
*/
二、异常处理
1、异常Exception
异常指的是程序运行时发生的不正常事件;异常能够被程序处理,保证程序继续运行下去;例如除数为0、文件没有找到、输入的数字格式不对……
System.out.println("程序出现异常:");
System.out.println(100/0);//出现异常没有被正确处理,不能往下运行
System.out.println("程序继续运行");
java.lang.ArithmeticException: / by zero
2、错误Error
错误程序没法处理,eg内存泄漏。发生错误后,一般虚拟机会选择终止程序运行,需要修改代码解决
int[] a=new int[1024*1024*1024];
//java.lang.OutOfMemoryError对空间超出JVM内存,内存溢出,只能把长度改小
Throwable类(顶级父类)
Throwable类有两个子类:Exception和Error
所有异常都是Exception类的直接或间接子类
所有错误都是Error的直接或间接子类
1、运行时异常 RuntimeException的子类都是运行时异常
非检测异常(unchecked Exception),这些异常在编译期不检测,程序中可以选择处理,也可以不处理,编译通过,如果不处理运行时会中断,但是编译没问题;
空指针异常NullPointerException
发生前提:当对一个空对象既没有初始化依然为null的对象调用属性或方法时
String str1 = "";//输出0,str1为空字符串,长度为0,存在
String str = null;//不存在
System.out.println(str.length());
//str为null,对象为null,调用length(),就会报NullPointerException异常
数学异常ArithmeticException
整数除以0
System.out.println(10.0/0);//**浮点型不抛出异常**,输出Infinity
System.out.println(10/0);//**整数抛出异常**java.lang.ArithmeticException
索引越界异常IndexOutOfBoundsException
数组索引:ArrayIndexOutOfBoundsException
字符串索引:StringIndexOutOfBoundsException
当访问字符串中的字符或数组中的元素超过了其长度时
//int[] a=new int[3];
//System.out.println(a[3]);//数组索引越界,出现异常java.lang.ArrayIndexOutOfBoundsException: 3(冒号左边异常类型,右边提示信息)
String str="hello";
//打印字符串索引5的字符,会出现异常StringIndexOutOfBoundsEx