Why is such a product coming?

It may be easy, but I don’t understand why the output goes as 1 4. And what is the function of the return statement on line 9?

public static void main(String[] args) {
    try{
        f();
    } catch(InterruptedException e){
        System.out.println("1");
        throw new RuntimeException();
    } catch(RuntimeException e){
        System.out.println("2");
        return;                    \\ Line 9
    } catch(Exception e){
        System.out.println("3");
    } finally{
        System.out.println("4");
    } 
        System.out.println("5");
}   
        static void f() throws InterruptedException{
            throw new InterruptedException("Interrupted");
    }

Thanks in advance.

+4
source share
6 answers

function f() throws InterruptedException, catch (, 1), catch ( ). , catch , , (, , ). , catch - ?.

, .

, try, ( catch). catch (, , ), .

catch, , ( ).

+2

, f() InterruptedException, 1, catch, finally , 4.

+1

1 , f() InterruptedException. Exception catch, . finally , 4.

+1
try{
    f();
} catch(InterruptedException e){
    System.out.println("1");
    throw new RuntimeException(); // this RuntimeException will not catch by 
                                  //following catch block
} catch(RuntimeException e){

, .

 try{
        f();
    } catch(InterruptedException e){
        System.out.println("1");
        try {
            throw new RuntimeException();// this RuntimeException will catch 
                                         // by the following catch 
        }catch (RuntimeException e1){
            System.out.println("hello");
        }
    } catch(RuntimeException e){
        System.out.println("2");
        return;
    } catch(Exception e){
        System.out.println("3");
    } finally{
        System.out.println("4");
    }
    System.out.println("5");

"

  1
  hello // caught the RunTimeException
  4 // will give you 2,but also going to finally block then top element of stack is 4
  5 // last print element out side try-catch-finally
+1

f() InterruptedException, 1. , , 4.

+1

f() InterruptedException, ,

catch(InterruptedException e){
        System.out.println("1");
        throw new RuntimeException();
}

prints → 1

, , ,

finally{
        System.out.println("4");
}

prints → 4

, , , .

+1

All Articles