码迷,mamicode.com
首页 > 其他好文 > 详细

简单的try-catch异常捕捉

时间:2016-09-02 00:18:09      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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异常捕捉

标签:

原文地址:http://www.cnblogs.com/webgavin/p/5831670.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!