return与finally执行优先级

public class Main{
	public static void main(String[] args) {
		System.out.println(test());
		
	}
	private static int test(){
		int[] a={1,2};
		try{
			a[2]=3;
			return 0;
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("ArrayIndexOutOfBoundsException");
			//return 1;
		}catch(RuntimeException e){
			System.out.println("RuntimeException");
			//return 1;
		}catch(Exception e){
			System.out.println("Exception");
			//return 1;
		}finally{
			System.out.println("finally");
			return 2;
		}
		//return 3;
	}
}

结果:

ArrayIndexOutOfBoundsException
finally
2

 

public class Main{
	public static void main(String[] args) {
		System.out.println(test());
		
	}
	private static int test(){
		int[] a={1,2};
		try{
			a[2]=3;
			//return 0;
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("ArrayIndexOutOfBoundsException");
			return 1;
		}catch(RuntimeException e){
			System.out.println("RuntimeException");
			return 1;
		}catch(Exception e){
			System.out.println("Exception");
			return 1;
		}finally{
			System.out.println("finally");
			return 2;
		}
		//return 3;
	}
}

结果:

ArrayIndexOutOfBoundsException
finally
2
 

public class Main{
	public static void main(String[] args) {
		System.out.println(test());
		
	}
	private static int test(){
		int[] a={1,2};
		try{
			a[2]=3;
			//return 0;
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("ArrayIndexOutOfBoundsException");
			return 1;
		}catch(RuntimeException e){
			System.out.println("RuntimeException");
			return 1;
		}catch(Exception e){
			System.out.println("Exception");
			return 1;
		}finally{
			System.out.println("finally");
			//return 2;
		}
		return 3;
	}
}

结果;

ArrayIndexOutOfBoundsException
finally
1

此处try里的return被注掉了,因为如果不注掉的话最后一个return就永远无法执行,会报错。

你可能感兴趣的:(JAVA)