zoukankan      html  css  js  c++  java
  • 关于try 和 throw 简单示例

    //每过一段时间,就总是会对try有点生疏,特别写了个程序来测试以下。加深印象。

    // 退出一段代码(即某个Method,或者某个块),有三种方法: throw,return,以及正常执行完。
    // 有时候 throw是底层抛出来的,你不处理,默认就throw了。
    // TestTry.java
    /**
     * 输出结果为:
    java.lang.Exception: test3() 抛出的异常
    	at test.TestTry.test3(TestTry.java:29)
    	at test.TestTry.test2(TestTry.java:16)
    	at test.TestTry.test1(TestTry.java:9)
    	at test.TestTry.main(TestTry.java:44)
    test1() 执行
    test2() 进入
    进入 test3()。。。
    test3() catch (Exception e)
    test2() catch (Exception e)
    test2() try catch 后面的内容...
    test1(),执行完test2之后 执行
    
     */
    public class TestTry {
    
    
    	public static void test1(){
    		System.out.println("test1() 执行");
    		//
    		test2();
    		//
    		System.out.println("test1(),执行完test2之后 执行");
    	}
    	public static void test2(){
    		System.out.println("test2() 进入");
    		try {
    			test3(true);
    			System.out.println("test2() try 后面的内容");
    		} catch (Exception e) {
    			System.out.println("test2() catch (Exception e)");
    			e.printStackTrace();
    		}
    		System.out.println("test2() try catch 后面的内容...");
    	}
    	
    	public static void test3(boolean isThrow) throws Exception{
    		System.out.println("进入 test3()。。。");
    		try {
    			if (isThrow) {
    				throw new Exception("test3() 抛出的异常");
    			}
    			//
    			System.out.println("test3() 抛出异常以后的try内容...");
    		} catch (Exception e) {
    			//
    			System.out.println("test3() catch (Exception e)");
    			throw e;
    		}
    		//
    		System.out.println("test3() try catch 后面的内容...");
    	}
    	
    	
    	public static void main(String[] args) {
    		test1();
    	}
    }
    



  • 相关阅读:
    UVA 439 Knight Moves
    UVA 673 Parentheses Balance
    UVa 536 Tree Recovery
    UVA 712 S-Trees
    UVA 12657 Boxes in a Line
    UVA 679 Dropping Balls
    UVA 1603 Square Destroyer
    UVA 1343 The Rotation Game
    UVA 1374 Power Calculus
    UVA 12558 Egyptian Fractions (HARD version)
  • 原文地址:https://www.cnblogs.com/lanzhi/p/6467127.html
Copyright © 2011-2022 走看看