在Java中的是通过Throwable以及其相关子类来对异常进行描述的,下面是我做的一个关于异常的脑图
Error: Error是程序中无法处理的错误,表示运行应用程序中教严重问题。
Exception: Exception是程序本身可以处理的异常,异常处理通常针对这种类型异常的处理。
Java中对异常处理是通过 try、catch、fianlly、throw、throws 五个关键字处理。
throw: throw将产生的异常抛出。
throws: throws声明将要抛出何种异常。
下面来看一个,java异常处理例子
public class Test {
public static void main(String[] args) {
try {
int a = 1 / 0;
} catch (RuntimeException e) {
System.out.println(e);
} finally {
System.out.println("我是finally");
}
System.out.println("异常之后的信息。。");
}
}
执行结果:
java.lang.ArithmeticException: / by zero
我是finally
异常之后的信息。。
加入return语句
public static void main(String[] args) {
try {
int a = 1 / 0;
} catch (RuntimeException e) {
System.out.println(e);
return ;
} finally {
System.out.println("我是finally");
}
System.out.println("异常之后的信息。。");
}
}
执行结果:
java.lang.ArithmeticException: / by zero
我是finally
Java里面用try catch异常处理之后,catch之后的代码也会执行,那还要finally有什么用啊?如果出现异常而catch中有return关键字,这样catch之后的代码就不会执行到了,所以需要释放资源的代码必须放在finally中。