异常
什么是异常
异常指程序运行中出现的不期而至的各种状况:如文件找不到,网络连接失败,非法字符等。
分类:
检查性异常:编译可见
运行时异常:运行可见
错误ERROR:编译检查不到
Error与Exception
Error:
- 由java虚拟机生成并抛出,一般与代码编写者无关
- java虚拟机运行错误(Virtual MachineError),虚拟机内存资源不足时会出现OutOfMemoryError。
- 类定义错误(NoClassDefFoundError)
Exception:
- RuntimeException(运行时异常)
- ArrayIndexOutOfBoundsException(数组下标越界)
- NullPointerException(空指针异常)
- ArithmeticException(算数异常)
- MissingResourceException(丢失资源)
- ClassNotFoundException(找不到类异常)
程序逻辑错误引起的,尽量避免其发生
区别:Error时致命错误,程序无法控制的。JVM会终止,而Exception可以在程序中处理
异常格式
关键词:
try,catch,finally,throw,throws
public class Test {
public static void main(String[] args) {
int a =1 ;
int b =0;
//捕获多个异常时,要从小到大
try {//监控异常
if(b == 0){
throw new ArithMeticException();//主动抛出异常
}
System.out.println(a/b);
}catch (Exception e) {//catch(想要捕获的异常类型// )捕获异常
System.out.println("Exception");
}catch (Throwable e){
System.out.println("Throwable");
}finally {//处理善后(可以不要)
System.out.println("finally");
e.printStackTrace();//为打印错误信息
}
}
public void a(){
b();
}
public void b(){
a();
}
}
捕获异常的快捷方式:Ctrl +Alt+t
public class Test {
public static void main(String[] args) {
try {
new Test().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
//方法中处理不了这个异常。方法上抛出异常
public void test(int a,int b) throws ArithmeticException{
if (b == 0){
throw new ArithmeticException();//主动抛出异常
}
}
}
自定义异常
public class Demo1 extends Exception{//自定义异常类
public Demo1(int detail) {
this.detail = detail;
}
private int detail;
public String toString(){
return "MyException{"+detail+"}";
}
}
public class Demo02 {//测试类
static void test(int a) throws Demo1 {
System.out.println("输入的值为:"+a);
if (a>10){
throw new Demo1(a);
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(1);
} catch (Demo1 demo1) {
System.out.println();
}
}
}