Nice programing

catch 및 finally에서 return 문 동작

nicepro 2020. 11. 10. 22:15
반응형

catch 및 finally에서 return 문 동작


다음 코드를보고 출력 동작을 설명하십시오.

public class MyFinalTest {

    public int doMethod(){
        try{
            throw new Exception();
        }
        catch(Exception ex){
            return 5;
        }
        finally{
            return 10;
        }
    }

    public static void main(String[] args) {

        MyFinalTest testEx = new MyFinalTest();
        int rVal = testEx.doMethod();
        System.out.println("The return Val : "+rVal);
    }

}

결과는 반환 Val : 10입니다.

Eclipse는 경고를 표시합니다 finally block does not complete normally..

catch 블록의 return 문은 어떻게됩니까?


다른 모든 것 이후에 실행 finally되기 때문에 의 하나에 의해 재정의됩니다 finally.

- 왜, 엄지 손가락의 규칙 때문이다 에서 돌아 오지 않았다finally . 예를 들어 Eclipse는 해당 코드 조각에 대한 경고를 표시합니다. "finally block does not complete normal"


finally항상 실행됩니다 (유일한 예외는 System.exit()). 이 동작은 다음과 같이 생각할 수 있습니다.

  1. 예외가 발생했습니다.
  2. 예외가 포착되고 반환 값이 5로 설정 됨
  3. 마지막으로 블록이 실행되고 반환 값이 10으로 설정됩니다.
  4. 함수는

VM의 낮은 수준의 레이아웃을 기억한다면 쉬운 질문입니다.

  1. 반환 값은 catch 코드에 의해 스택에 배치됩니다.
  2. 그 후 finally 코드가 실행되고 스택의 값을 덮어 씁니다.
  3. 그런 다음 메서드는 호출자가 사용할 최신 값 (10)을 반환합니다.

이와 같은 사항에 대해 확실하지 않은 경우 기본 시스템에 대한 이해로 돌아가십시오 (궁극적으로 어셈블러 수준으로 이동).

( 재미있는 사이드 노트 )


finally(일치하는 시도가 실행 된 경우) 블록은 항상 실행되므로 하나에있어서 반환 전에 5 catch블록, 상기 실행 finally블록 되돌아 10.


enter image description here

Finally block always get executed unless and until System.exit() statement is first in finally block.

So here in above example Exection is thrown by try statement and gets catch in catch block. There is return statement with value 5 so in stack call value 5 gets added later on finally block executed and latest return value gets added on top of the stack while returning value, stack return latest value as per stack behavior "LAST IN FIRST OUT" so It will return value as 10.


the finally section will execute always execute. e.g. if you have any thing to release, or log out sort of thing, if error occur then go to catch section else finally will execute.

Session session //  opened some session 
try 
{
 // some error 
}
catch { log.error }
finally 
{ session.logout();}

it should not used to return anything. you can use outside of.

참고URL : https://stackoverflow.com/questions/5701793/behaviour-of-return-statement-in-catch-and-finally

반응형