Java异常是一个描述在代码段中发生的出错的情况,Java异常可能是由Java运行时系统产生,或者是由你自己写的代码产生。被Java抛出的异常与违反语言规范或超过Java执行环境限制的基本错误有关。手工编码产生的异常基本上用于报告方法调用程序的出错状况。
Java异常处理通过5个关键字控制:try、catch、throw、throws和finally。
我们之前学习也遇到过不少的Java异常,比如空异常NullPointerException、数组下标越界异常ArrayIndexOutOfBoundsException、类型转换异常ClassCastException等。
而这些异常都是可以捕获并能处理的。
注意:任何异常抛出之后,程序也将不会往下继续走了。
下面看一段例子:
try {
int[] a=new int[3];
System.out.println(a[10]);//此时访问a[10]肯定会抛ArrayIndexOutOfBoundsException异常
//catch块能够捕获try块中抛出的异常
} catch (NullPointerException e) {
//如果异常是NullPointerException异常,那么在这里异常就会被捕获,如果不是,就会继续往下看能不能被下一个catch块捕获。
System.out.println("产生了空指针异常");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("访问数组下标越界了");
} catch (Exception e) {
//所有异常的父类,不管会抛出什么异常,都会在这里被捕获
System.out.println("出异常了");
}
在这段代码中,声明了我想要的异常监控包含在一个try块中,如果在try中发生异常,它会被抛出。在下面我可以用catch关键字来捕获try块中产生的异常并自己可以处理这个异常。
系统产生的异常会在Java运行时系统自动抛出。但是也可以手动抛出一个异常,让上一层代码去捕获处理,用关键字throw。但是需要在方法后面通过throws关键字定义可能抛出的异常。
public static void main(String[] args) throws Exception{
int a=10;
int b=0;
int c=a-b;
if(c==0){
throw new Exception("抛出这个异常");
}
}
而finally块的代码不管try块中会不会抛出异常,都会执行finally块中的代码,而这里的代码一般用作关闭数据库连接或者关闭IO流对象以便不浪费资源。
public class Demo {
public static void main(String[] args) {
try {
int a=10/0;
} catch (Exception e) {
System.out.println("出现了异常");
}finally{
System.out.println("finally块的代码不管上面的try块会不会出现异常都会被执行");
}
}
}
运行结果:
出现了异常
finally块的代码不管上面的try块会不会出现异常都会被执行
我们也能够定义自己的异常类
定义自己的异常类需要继承Exception类(Exception类本身就是Throwable类的子类)
//自定义的异常需要继承Exception或者Throwable类
class MyException extends Exception{
private String str;
public MyException(String str) {
this.str=str;
}
//打印输出异常信息
public void print(){
System.out.println(str);
}
}
一个完整的例子:public class Test{
//计算a/b
public int f(int a,int b) throws MyException{
//如果除数等于0,那么就抛出一个MyException异常
if(b==0){
throw new MyException("抛出了这个异常:除数不能等于0");
}
return a/b;
}
public static void main(String[] args) {
Test t=new Test();
try {
t.f(10, 0);
//在这里捕获f()方法中抛出的MyException异常
} catch (MyException e) {
e.print();
}
}
}
//自定义的异常需要继承Exception或者Throwable类
class MyException extends Exception{
private String str;
public MyException(String str) {
this.str=str;
}
public void print(){
System.out.println(str);
}
}
运行结果:
抛出了这个异常:除数不能等于0