简单的try-catch异常捕捉

Posted 是个传颂厨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单的try-catch异常捕捉相关的知识,希望对你有一定的参考价值。

package com.test;

public class TryCatchTest {

    public static void main(String[] args) {
        TryCatchTest tct = new TryCatchTest();
        int result = tct.test();
        System.out.println("test()方法执行完毕,返回"+result);
        int result2= tct.test2();
        System.out.println("test2()执行完毕");
        int result3 = tct.test3();
        System.out.println("test3()执行完毕");

    }
    
    //创建divider(除数)
    //result结果
    //try-catch捕获while循环
    public int test(){
        int divider = 10;
        int result = 100;
        try {
            while(divider >-1){
                divider--;
                result = result +100/divider;
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();//打印错误原因与位置
            System.out.println("循环抛出异常");
            return -1;
        }
    }
    
    public int test2(){
        int divider = 10;
        int result = 100;
        try {
            while(divider >-1){
                divider--;
                result = result +100/divider;
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();//打印错误原因与位置
            System.out.println("循环抛出异常");
            return result = 999;
        }finally{
                System.out.println("这是finally");
                System.out.println("result"+result);
                }
    }
    
    //如果try-catch语句中无返回,就会调用之外的return 
    public int test3(){
        int divider = 10;
        int result = 100;
        try {
            while(divider >-1){
                divider--;
                result = result +100/divider;
            }
            
        } catch (Exception e) {
            e.printStackTrace();//打印错误原因与位置
            System.out.println("循环抛出异常");
            
        }finally{
                System.out.println("这是finally");
                System.out.println("result"+result);
                }
        System.out.println("test3运行完毕");
        return -1;
    }
}

 

以上是关于简单的try-catch异常捕捉的主要内容,如果未能解决你的问题,请参考以下文章

Java try-catch自定义捕捉异常

java中 try-catch语句

再学try-catch

还在滥用try-catch处理异常?看看springboot的优雅实现吧

java中异常抛出后代码还会继续执行吗

异常和TCP通讯