异常分类
Java所有的异常(Exception)都是派生自Throwable,异常是可以被捕获的。而错误(Error)是不能被捕获的。这里详细介绍Java的异常捕获机制(try-catch语句)
1.最简单的try-catch语句
int x=10;
try {
System.out.println(x); //代码块
int y=x/0;
System.out.println(y);
}
catch(Exception e) {
e.printStackTrace(); //catch块
System.out.println(x);
}
捕获异常如下
从这个例子中我们可以看出,try中的代码报错,则下面的代码不会再执行,转而执行catch代码块
2.自定义异常
自定义异常一般情况下要继承RuntimeException类
public class define_exception extends RuntimeException {
/**
* 重写fillInStackTrace()方法
*/
private static final long serialVersionUID = 1L;
public synchronized Throwable fillInStackTrace() {
System.out.println("Exception occurring");
return this;
}
public static void main(String[] args) throws define_exception{
throw new define_exception();
}
}
3.多重catch语句
一个代码块可能产生多个异常,这时,我们可以采用多重catch语句捕获多个异常
public class Multi_Catch {
public static void main(String[] args){
try {
System.out.println(10/0);
}
catch(define_exception e) {
e.printStackTrace();
}
catch(RuntimeException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
父类异常一定要写在子类异常的后面,因为父类异常会捕获所有类型的子类异常,否则会报错
4.try-catch-finally
finally代码块无论如何一定执行
public class Try_Catch_Finally {
public static void main(String[] args){
try {
System.out.println("Normal operation1");
int x=10/0;
System.out.println("Normal operation2");
}
catch(Exception e){
System.out.println("Normal operation3");
}
finally {
System.out.println("Normal operation4");
}
}
}
运行结果如下: