java异常与捕获
几乎所有的代码里面都会出现异常,为了保证程序在出响异常之后可以正常执行完毕,就需要进行异常处理。
Java异常体系的类继承结构如下
产生一个异常
public class TestDemo2 {
public static void main(String[] args) {
System.out.println("1、开始计算");
System.out.println("2、进行计算:"+10/0);
System.out.println("3、计算结束");
}
}
现在程序产生了运算异常,异常语句之前可以正常执行,异常产生程序就结束了,为了继续执行程序我们需要进行异常处理
public class TestDemo2 {
//一旦程序发生异常,程序将不会向下继续执行
public static void main(String[] args) {
System.out.println("1、开始计算");
try {
System.out.println("2、进行计算:"+10/0);
}catch (ArithmeticException e){
e.printStackTrace(); //写出异常
System.out.println("算术发生异常");
}finally {//永远都会执行 作用:用来关闭资源。
System.out.println("finally执行");
}
System.out.println("3、计算结束");
}
}
注:java.lang.ArithmeticException是在异常信息栈。
throws关键字和throw关键字。
throws:表示如果出现异常后不希望进行处理,就是用throws抛出。
throw:表示人为进行异常的抛出,之前所有异常类的对象都是由JVM自动进行实例化操作的,如果希望用户手动抛出异常就用throw。
面试题:请解释throws和throw的区别
1丶throw用于方法内部,主要表示手工抛出异常(这个对象可以是自己实例化的,也可以是已经存在的)。
2丶throws主要在方法声明上使用,明确告诉用户本方法可能产生的异常,同时该方法可能不处理此异常。
主类抛出异常
public class TestDemo1{
public static void main(String[] args) throws Exception {
System.out.println(calculate(10,0));
}
public static int calculate(int x,int y) throws Exception{
return x/y;
}
}
这时主方法将异常继续向上抛,交给JVM进行异常的处理,也就是采用默认的方式,输出异常信息,而后结束程序执行。
throw关键字
public class TestDemo1{
public static void main(String[] args) {
try {
throw new Exception("抛出一个异常");
}catch (Exception e){
e.printStackTrace();
}
}
}
自定义异常
class AddException extends Exception{
public AddException(String str){
super(str);
}
}
public class TestDemo1{
public static void main(String[] args) throws Exception {
int num1 = 20;
int num2 = 30;
if (num1 + num2 == 50) {
throw new AddException("错误的相加操作");
}
}
}