什么是异常
程序非正常编译和运行
-
语法错误不是异常,语法错误是编译器检查出现的错误,虽然在编译时就检查的受查异常也是Exception的子类
java对于异常
java以异常类的形式对异常进行封装,通过异常类内部机制处理各种异常问题。
没有异常机制存在的缺点: (代码出现很多if/else)
使用方法的返回值来表示异常情况有限,无法穷举所有的异常情况.
增加代码的复杂性,可读性不好.
程序的可维护性降低.
java异常类
java异常处理
Error:出现无法处理的异常,不能被捕获处理,程序不能运行,通常为JVM异常
RuntimeException:运行时异常
包括以下
ArithmeticException:
算数异常
ClassCastException:转换异常
IndexOutOfBoundsException:越界异常
ArrayIndexOutOfBoundsException:数组越界异常
NullPointerException:空指针异常
ArrayStoreException:数组存储与声明类型不兼容对象异常
异常处理
try( <在这里打开的资源自动关闭>){
}
catch(IOException<异常类型> e){
}
catch(RuntimeException<异常类型> e){
}
catch(Exception<异常类型> e){
}
finally{
}
-
一个try、catch、finally块之间不能插入任何其它代码,finally通常用于关闭资源
-
catch可以有多个,try和finally只能有一个
-
try后面必须要跟catch、finally其中的一个,即但一个try、catch、finally语句只能省略catch、finally中的一个。
-
一个try后面可以跟多个catch,但不管多少个,最多只会有一个catch块被执行。
-
catch的异常类型要从小到大。如
ArithmeticException, ArrayIndexOutOfBoundsException,ClasscastException,RuntimeException,Exception,依次catch
特殊情况
private static int test1()
{
try{
return 1;
}finally{
return 100;
}
}
输出结果为 100
private static int test3()
{
int a=1;
try{
return a;
}finally{
++a;
}
}
结果为1
异常抛出
throw 抛出一个异常对象,写在语句中,throws写在方法体后面,抛出 一类异常
public class ThrowsTest {
public static void main(String[] args) throws ArithmeticException
{
System.out.println("你好!这里是异常抛出测试例子");
double a=10;double b=0;
double d=devide(a,b);
System.out.println("double:"+d);
d=devide((int)a,(int)b);
System.out.println("int:"+d);
}
public static double devide(double a,double b) {
double result;
try{
result=a/b;
}catch(ArithmeticException e)
{
e.printStackTrace();
throw e;
}
return result;
}
public static int devide(int a,int b) {
int result;
try{
result=a/b;
}catch(ArithmeticException e)
{
throw e;
// System.out.println("throw 会像return 一样结束当前方法");
}
return result;
}
}
输出结果:
你好!这里是异常抛出测试例子
double:Infinity
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.model.ThrowsTest.devide(ThrowsTest.java:28)
at com.model.ThrowsTest.main(ThrowsTest.java:10)
自定义异常
自定义一个类继承一个异常类,通常为RuntimeException或者Exception例如下面的MyRuntimeException
:
public class Main{
public static void main(String[] args) {
throw new MyRuntimeException("当前你没有进行任何操作");
}
}
class MyRuntimeException extends RuntimeException{
public MyRuntimeException(){
super();
}
public MyRuntimeException(String message){
super(message);
}
public MyRuntimeException(String message,Throwable cause){
super(message,cause);
}
}
RuntimeException 及其子类可以不处理。
异常转译:捕获原始的异常,把它转换为一个新的不同类型的异常,再抛出新的异常.
异常链:把原始的异常包装为新的异常类,从而形成多个异常的有序排列,
例如:
try {
dosomething();
} catch (Exception e) {
e.printStackTrace();
throw new MyRuntimeException("我的自定义异常",e);
//如果这样写,则为抹杀原本的异常,并没有加入异常链
//throw new MyRuntimeException("我的自定义异常");
}
printStackTrace()为打印异常跟踪栈信息,getMessage()为获取异常描述信息
网友评论