Exception Handling Try it without catch, but finally

public class ExceptionTest {
    public static void main(String[] args) {
        ExceptionTest et = new ExceptionTest();
        try {
            et.testMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }   
    public int testMethod()  {
        try {           
            throw new Exception();
        }finally {
            return 4;
        }
    }

The above code works fine, but when I change the return type testMethod()to void and change the string return 4;to System.out.println("some print msg");, there is a compilation problem.

Can someone please give a decision why it gives a compilation error?

+4
source share
2 answers

The problem is that the return statement inside the finally block raises any exception that might be thrown into the try block that should be thrown.

, , , - , , , .

Java http://thegreyblog.blogspot.it/2011/02/do-not-return-in-finally-block-return.html

+4

Java 8:

public class ExceptionTest {
    public ExceptionTest() {

    }

    public static void main(String[] args) {
        ExceptionTest et = new ExceptionTest();
        try {
            et.testMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void testMethod() throws Exception {
        try {
            throw new Exception();
        } finally {
            //return 4;
            System.out.println("hello finally");
        }
    }
}

"throws" .

:

hello finally
java.lang.Exception
    at ExceptionTest.testMethod(ExceptionTest.java:17)
    at ExceptionTest.main(ExceptionTest.java:9)
0

All Articles