1、什么是异常
程序运行出现的,导致程序无法正常运行的错误,叫做异常
- 异常的父类Throwable(使用ctrl+t,显示继承关系),主要包含两个子类:
- Error:一般是JVM即Java虚拟机运行中出现了问题,不用处理,也没法处理。
- Exception 分为两种,一种是RuntimeException,这种错误可以处理,也可以不处理,可以使用try catch,也可以不用try catch;另一种是非RuntimeException,必须使用try catch
2、常见RuntimeException
- NullPointerException 空指针异常
- IndexOutofBoundException 数组下标越界异常
- NumberFormatException 数据格式异常
- IllegalArgumentException 非法参数异常
- ArithmeticException 算术异常
- IllegalStateException 非法语句异常
3、常见非RuntimeException
- ClassNotFoundException 类找不到异常
4、抛出异常与处理异常
![](https://img.haomeiwen.com/i4593121/f27562d349d9b640.png)
Math类:
package javastudy;
public class Math {
public static int add(String a,String b){
int sum=Integer.parseInt(a);
sum+=Integer.parseInt(b);
return sum;
}
}
Testit类
package javastudy;
public class Testit {
public static void main(String[] args) {
System.out.println(Math.add("100","101"));
}
}
![](https://img.haomeiwen.com/i4593121/ae4860a5f6071b69.png)
若此时将字符串改为“100a”,此时转成整数时会报错
![](https://img.haomeiwen.com/i4593121/6e5d568990695c25.png)
其报错原因是因为主函数在调用Math时,在转换时出错,这时在Math类中使用try catch,这样避免在调用的函数时 传出错误
package javastudy;
public class Math {
public static int add(String a,String b){
try {
int sum=Integer.parseInt(a);
sum+=Integer.parseInt(b);
return sum;
} catch (Exception e) {
// TODO: handle exception
return -1;
}
}
}
此时,在执行上述的System,会输出-1
![](https://img.haomeiwen.com/i4593121/ef47975a9b4f32b3.png)
在发生错误时,不处理,逐层的往外面扔。下面示例中,由于没有aaa的类,因此会报错
public class Math {
public static void test() throws ClassNotFoundException{ //此函数可能会发生ClassNotFound的错误
Class.forName("aaa");
}
}
在testit类中
public class Testit {
public static void main(String[] args) throws ClassNotFoundException {
Math.test();
}
}
由于是Math函数的错误,但是却扔出错误,然后testit主函数又扔出,由于是主函数,所以只能是扔给虚拟机
![](https://img.haomeiwen.com/i4593121/ae27fbd7c3811e36.png)
5、在try catch中添加finally
public class Math {
public static int add(String a,String b){
try {
int sum=Integer.parseInt(a);
sum+=Integer.parseInt(b);
return sum;
} catch (Exception e) {
// TODO: handle exception
return -1;
}
finally {
System.out.println("finally"); //不管是否出错,finally都会被执行
}
![](https://img.haomeiwen.com/i4593121/0632bc179b1a89e2.png)
![](https://img.haomeiwen.com/i4593121/a1dc8d91b00a83da.png)
网友评论