首页 > 代码库 > java之finally的用法

java之finally的用法

package com.smbea.demo.tryCatchFinally;

/**
 * java之finally的用法
 * @author hapday
 * @2017年2月5日 @上午12:21:16
 */
public class TryCatchFinallyDemo {

	public static void main(String[] args) {
		hasException();
		System.out.println("\n——————————————————————————————————————————————————————————————————\n");
		noneException();
		System.out.println("\n——————————————————————————————————————————————————————————————————\n");
		System.out.println(hasReturnAndNoneException());
		System.out.println("\n——————————————————————————————————————————————————————————————————\n");
		System.out.println(hasReturnAndHasException());
	}

	/**
	 * 有异常发生
	 */
	public static void hasException() {
		int divisor = 10;
		int dividend = 0;
		
		try {
			System.out.println(divisor + " / " + dividend + " = " + (divisor / dividend));
		} catch (Exception e) {
			System.out.println("这里的代码只有出现异常后执行...");
			e.printStackTrace();
		} finally {
			System.out.println("这里的代码始终执行,不论有没有发生异常或在 try 块中出现 return 语句,都不受影响...");
		}
	}

	/**
	 * 无异常发生
	 */
	public static void noneException() {
		int divisor = 10;
		int dividend = 10;
		
		try {
			System.out.println(divisor + " / " + dividend + " = " + (divisor / dividend));
		} catch (Exception e) {
			System.out.println("这里的代码只有出现异常后执行...");
			e.printStackTrace();
		} finally {
			System.out.println("这里的代码始终执行,不论有没有发生异常或在 try 块中出现 return 语句,都不受影响...");
		}
	}
	
	/**
	 * try 块中有 return 语句但是无异常
	 * @return
	 */
	@SuppressWarnings("finally")
	public static int hasReturnAndNoneException() {
		int divisor = 10;
		int dividend = 10;

		try {
			System.out.println(divisor + " / " + dividend + " = " + (divisor / dividend));
			
			divisor *= 2;

			System.out.println("divisor = " + divisor);
			
			return divisor;
		} catch (Exception e) {
			System.out.println("这里的代码只有出现异常后执行...");
			e.printStackTrace();
		} finally {
			System.out.println("这里的代码始终执行,不论有没有发生异常或在 try 块中出现 return 语句,都不受影响...");
			
			divisor *= 3;
			
			System.out.println("divisor = " + divisor);

			return divisor;
		}
	}

	/**
	 * try 块中有 return 语句但是有异常
	 * @return
	 */
	@SuppressWarnings("finally")
	public static int hasReturnAndHasException() {
		int divisor = 10;
		int dividend = 0;
		
		try {
			System.out.println(divisor + " / " + dividend + " = " + (divisor / dividend));
			
			divisor *= 2;

			System.out.println("divisor = " + divisor);
			
			return divisor;
		} catch (Exception e) {
			System.out.println("这里的代码只有出现异常后执行...");
			e.printStackTrace();
		} finally {
			System.out.println("这里的代码始终执行,不论有没有发生异常或在 try 块中出现 return 语句,都不受影响...");
			
			divisor *= 3;
			
			System.out.println("divisor = " + divisor);

			return divisor;
		}
	}
}

  

java之finally的用法