return finally 与 System.exit(n)

问题:System.exit(n);的含义以及作用

说明:
public static void exit(int status)终止当前正在运行的 Java 虚拟机。
参数用作状态码;根据惯例,非 0 的状态码表示异常终止。
该方法调用 Runtime 类中的 exit 方法。该方法永远不会正常返回。
调用 System.exit(n) 实际上等效于调用:
Runtime.getRuntime().exit(n)

一、运行顺序

1.finally 与 return

return 运行后 执行 finally

return 是返回到调用方法的上一层

2.finally 与 System.exit(0)

System.exit(0) 不再运行其后面的代码

System.exit() 返回到调用方法的最上一层

3.示例



public class returnTestMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int resultMethod = returnMethod();
		System.out.println(resultMethod);
	}
	
	/**
	 * return 与 finally 
	 * return 是跳出当前的方法到上一层的方法中
	 * @return
	 */
	public static int returnMethod(){
		try {
			
			int a = 0 / 0 ;
			System.out.println("try method "+a);
			return 0 ;
		} catch (Exception e) {
			System.out.println("error method");
			// 直接跳出到程序的最上一层,终止程序运行
//			System.exit(0);
			return 1 ;
		}finally{
			System.out.println("finally method");
			// 此处添加返回值,始终返回 2 
//			return 2 ;
		}
		
	}

}



猜你喜欢

转载自mingyundezuoan.iteye.com/blog/2209972
今日推荐