Java学习笔记之异常(二)

try-catch 自己处理异常

如果异常出现的话,会立刻终止程序,所以我们得处理异常:
1.该方法不处理而是声明抛出,由该方法的掉用者来处理(throws)。
2.在方法中使用ty-catch的语句块来处理异常。
try-catch的方式就是捕获异常
捕获异常: Java中対异常有针対性的语句进行捕获,可以対出现的昇常进行指定方式的处理。
注意事项:

  1. try中可能会抛出多个异常対象,那么就可以使用多个catch来处理这些昇常対象
  2. 如果try中产生了异常,那么就会执行catch中的异常处理逻辑,执行完毕catch中的处理逻辑,继续执行try…catch之后的代码如果try中没有产生异常, 那么就不会执行catch中异常处理逻辑,执行完try中的代码,继续执行try…catch之后的代码
public class DemoFive {
    public static void method() throws IOException{

    }
    public static void main(String[] args) {
        try{
            method();//可能产生异常的代码
        }catch (NullPointerException e)
        {
            //处理异常逻辑
        }catch (IOException n){
            //处理异常逻辑
        }
    }
}

Throwable3个异常处理方法

1.getMessage() 返回此 throwable 的详细消息字符串。
2.printStackTrace() 将此 throwable 及其追踪输出至标准错误流。
3.toString() 返回此 throwable 的简短描述。

public class DemoException {
    public static void main(String[] args)throws ParseException {
        int []a = {1,2,3};
        try {
            //可能要出现异常的代码
            System.out.println(a[3]);
        }catch (Exception e)
        {
            System.out.println("getMessage()打印:"+e.getMessage());
            System.out.println("toString()打印:"+e.toString());
            System.out.println("-------------------------------");
            e.printStackTrace();
        }
    }
}

输出结果:

getMessage()打印:Index 3 out of bounds for length 3
toString()打印:java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
-------------------------------
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at com.lg.demo06.DemoException.main(DemoException.java:13)

finally代码块

public class NewDemo {
    public static void main(String[] args) {
        System.out.print(getNumber(0));
        System.out.print(getNumber(1));
        System.out.print(getNumber(2));
        System.out.print(getNumber(4));
    }

    public static int getNumber(int num) {
        try {
            int result = 2 / num;

            return result;
        } catch (Exception exception) {

            return 0;
        } finally {
            if (num == 0) {

                return -1;
            }
            if (num == 1) {

                return 1;
            }
        }
    }
}

结果:

"E:\JAVA\IntelliJ IDEA 2019.3.2\jbr\bin\java.exe" "-javaagent:E:\JAVA\IntelliJ IDEA 2019.3.2\lib\idea_rt.jar=55945:E:\JAVA\IntelliJ IDEA 2019.3.2\bin" -Dfile.encoding=UTF-8 -classpath E:\JAVA\project\day06-code\out\production\day06-code com.lg.demo06.NewDemo
-1110
Process finished with exit code 0

解析:
try,catch,finally中:
num=0,捕获异常,执行catch语句,catch中返回0,执行finally语句,finally语句中返回-1,于是返回finally中的-1;
num=1,try中返回2,执行finally语句,finally语句中返回1,于是返回finally中的1;
num=2,try中返回1,执行finally语句,finally语句中没有返回,于是返回try中的1;
num=4,try中返回0,执行finally语句,finally语句中没有返回,于是返回try中的0.

规则:
1.try块是必须的,catch块和finally块都是可选的,但必须存在一个或都存在。try块不能单独存在。
2.try块里的语句运行中出现异常会跳过try块里其他语句,直接运行catch里的语句。
3.无论try块中是否有异常,无论catch块中的语句是否实现,都会执行finally块里的语句。
4.如果try块或catch块中有return语句,finally块里的语句会执行在try块或catch块中的return语句前。
5.如果finally块里有return语句,则直接返回,而不执行try块或catch块里的return语句。
6.只有一种办法不执行finally块里的语句,那就是调用System.exit(1);方法,即退出java虚拟机。

以上内容引用自 https://blog.csdn.net/weixin_43610698/article/details/95955571
关于编译异常和运行异常https://www.cnblogs.com/AbelZone/p/10049997.html

不执行finally的情况:

public class NewDemo {
    public static void main(String[] args) {
       getNumber();
    }
    public static void getNumber() {
        try {
            System.out.println("try");
            System.exit(1);

        }  finally {
            System.out.println("finally");
        }
    }
}
没有System.exit(1);的情况
"E:\JAVA\IntelliJ IDEA 2019.3.2\jbr\bin\java.exe" "-javaagent:E:\JAVA\IntelliJ IDEA 2019.3.2\lib\idea_rt.jar=56548:E:\JAVA\IntelliJ IDEA 2019.3.2\bin" -Dfile.encoding=UTF-8 -classpath E:\JAVA\project\day06-code\out\production\day06-code com.lg.demo06.NewDemo
try
finally
有System.exit(1);的情况
"E:\JAVA\IntelliJ IDEA 2019.3.2\jbr\bin\java.exe" "-javaagent:E:\JAVA\IntelliJ IDEA 2019.3.2\lib\idea_rt.jar=56561:E:\JAVA\IntelliJ IDEA 2019.3.2\bin" -Dfile.encoding=UTF-8 -classpath E:\JAVA\project\day06-code\out\production\day06-code com.lg.demo06.NewDemo
try

finally一般用于资源释放,无论是否出现异常都要执行的代码。

多个异常的捕获处理

1.多个异常分别处理
2.一次捕获多次处理
3.多个异常一次捕获,一次处理

public class NewDemo {
    public static void main(String[] args) {
        //1.多个异常分别处理
     /*   try{
            List<Integer> list = List.of(1,2,3);
            System.out.println(list.get(4));
        }catch (IndexOutOfBoundsException e)
        {
            System.out.println(e);
        }
        try{
            int arr[] = {1,2,3};
            System.out.println(arr[3]);
        }catch (ArrayIndexOutOfBoundsException e)
        {
            System.out.println(e);
        }*/
        //2.一次捕获多次处理
        /**
         * 注意事项
         * catch中定义的异常变量,若果有子父类关系,子类异常变量卸载上边
         * 下列代码中IndexOutOfBoundsException是ArrayIndexOutOfBoundsException
         * 的父类,否则会报错*/
       /* try{
            List<Integer> list = List.of(1,2,3);
            System.out.println(list.get(4));
            int arr[] = {1,2,3};
            System.out.println(arr[3]);
        }catch (ArrayIndexOutOfBoundsException e)
        {
            System.out.println(e);
        }catch (IndexOutOfBoundsException e)
        {
            System.out.println(e);
        }*/
       //3.多个异常一次捕获,一次处理
        try{
            List<Integer> list = List.of(1,2,3);
            System.out.println(list.get(4));
            int arr[] = {1,2,3};
            System.out.println(arr[3]);
        }catch (Exception e)
        {
            System.out.println(e);
        }
    }
}

throw和throws的区别:

1、throw代表动作,表示抛出一个异常的动作;throws代表一种状态,代表方法可能有异常抛出
2、throw用在方法实现中,而throws用在方法声明中
3、throw只能用于抛出一种异常,而throws可以抛出多个异常

public class DemoException {
    public static void main(String[] args) {
        //method(null);
        methodOne();
    }
    /*
    * 表示抛出一个异常的动作
    * throw用在方法实现中
    * throw只能用于抛出一种异常*/
    public static void method(int arr[])
    {
        if(arr == null){
            throw new NullPointerException("空指针异常");
        }
    }
    /*
    * throws代表一种状态,代表方法可能有异常抛出
    * throws用在方法声明中
    * 而throws可以抛出多个异常*/
    public static void methodOne() throws  IndexOutOfBoundsException,
            NullPointerException
    {
        int two[] = {1,2,3};
        System.out.println(two[3]);
    }
}

子父类异常

如果父类抛出了多个异常,子类重写父类方法时,抛出和父类相同的异常或者父类异常的子类或者不抛出异常。
父类方法没抛出异常,子类重写父类该方法时也不抛出异常,只能捕获处理,不能声明抛出。

public class Father {
    public void method() throws IndexOutOfBoundsException,NullPointerException{}
    public void method1() throws IndexOutOfBoundsException{}
    public void method2() throws Exception{}
    public void method3(){}
}
class Son extends Father
{
    //父类抛出了多个异常,子类重写父类方法时,抛出和父类相同的异常
    @Override
    public void method() throws IndexOutOfBoundsException,NullPointerException{}
    //父类抛出了多个异常,子类重写父类方法时,抛出父类异常的子类
    @Override
    public void method1() throws ArrayIndexOutOfBoundsException{}
    //父类抛出了多个异常,子类重写父类方法时,不抛出异常
    @Override
    public void method2(){}
    //父类未抛出异常,子类重写父类方法时也不抛出异常,只能捕获处理异常
    @Override
    public void method3()
    {
        try {
            throw new Exception("编译异常");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

自定义异常类

必须继承Exception或RuntimeException
继承Exception:该异常类为编译异常,必须处理这个异常,抛出throws或者try-catch
继承RuntimeException:该异常类为运行期异常类,不用处理,交给JVM,中断处理

public class RegisterException extends Exception{

    public RegisterException(){
        super();//调用父类空参
    }
    public RegisterException(String s){
        super(s);//调用父类有参
    }
}
发布了22 篇原创文章 · 获赞 0 · 访问量 438

猜你喜欢

转载自blog.csdn.net/ENDEAVOR__/article/details/104854994
今日推荐