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; } }