您的位置:首页 > 编程语言 > Java开发

java异常处理机制finally中的return返回

2015-09-07 11:19 573 查看
1、概述

在 Java 中,所有的异常都有一个共同的父类 Throwable。

Throwable: 有两个重要的子类:Exception(异常)和 Error(错误),两者都是
Java 异常处理的重要子类,各自都包含大量子类。

Error(错误):是程序无法处理的错误,表示运行应用程序中较严重问题。大多数错误与代码编写者执行的操作无关,比如jvm虚拟机内部错误,或者其他系统硬件错误,这些异常发生时,Java虚拟机(JVM)一般会选择线程终止。

Exception(异常):是程序本身可以处理的异常。
Exception 类有一个重要的子类 RuntimeException。RuntimeException 类及其子类表示程序编译运行时候的异常。例如,若试图使用空值对象引用、除数为零或数组越界,则分别引发运行时异常(NullPointerException、ArithmeticException)和 ArrayIndexOutOfBoundException。

java异常通常又分为:检查异常(checked
exceptions)和不检查异常(unchecked exceptions)

可检查异常即编译器在编译时检查的额异常(eclipse直接报错的),代码编译不会通过的。不检查异常编译器检测不出来的异常,例如数组越界异常,类找不到异常,空指针异常等。下图为java异常继承层次结构图。



2、捕获异常 try catch finally
(1)try catch
有return

public class Test0907 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(new Test0907().haha());
	}
   public int  haha(){
	try {
		return 0;
	} catch (Exception e) {
		return 1;
	}finally{
		System.out.println("finally");
	}
}
}
结果输出:

finally
0
可见当try和catch里面有return语句时候,finally中的代码会在方法返回之前执行。
(2)try catchfinally 有return

public class Test0907 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(new Test0907().haha());
	}
   public int  haha(){
	try {
		return 0;
	} catch (Exception e) {
		return 1;
	}finally{
		return 0;
	}
}
}
结果输出:0

当try
、finally均有return时,finally中return则覆盖了 try中的return返回值,成为方法的返回值。
(3)当有异常抛出时

public class Test0907 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(new Test0907().haha());
	}
   public int  haha(){
	try {
		int i =1/0;
		return 0;
	} catch (Exception e) {
		e.printStackTrace();
		return 1;		
	}finally{
		System.out.println("finally");
	}
}
}
结果输出:

finally

1

java.lang.ArithmeticException: / by zero

at com.fbl.Test0907.haha(Test0907.java:13)

at com.fbl.Test0907.main(Test0907.java:9)

此时和情况(1)保持一致,也是catch里面有return语句时候,finally中的代码会在方法返回之前执行。

public class Test0907 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(new Test0907().haha());
	}
   public int  haha(){
	try {
		int i =1/0;
		return 0;
	} catch (Exception e) {
		e.printStackTrace();
		return 1;		
	}finally{
		System.out.println("finally");
		return 2;	
	}
}
}
结果输出:

java.lang.ArithmeticException:
/ by zero

at com.fbl.Test0907.haha(Test0907.java:13)

at com.fbl.Test0907.main(Test0907.java:9)

finally

2

方法抛出了异常,但是依然执行了finally中的代码块,并且输出return的返回值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: