Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why such output is coming?

It might be easy but I don't understand why the output is coming as 1 4. And what is the function of the return statement at 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.

like image 297
Leo Avatar asked Mar 19 '23 05:03

Leo


1 Answers

Your function f() throws InterruptedException, which is caught by the first catch block (hence it prints 1), but this catch block cannot throw other exceptions (if it is not thrown by your method), Hence, no other catch block can catch your excception and therefore finally is executed (finally executes in every case except those silly infinite loop cases). you can refer to Exception thrown inside catch block - will it be caught again?.

I hope it helps.

Just to summarize, you can throw any exception from try block & it will be caught (if there is a good catch block). But from catch block only those exceptions can be thrown (and consequently caught by) which your method throws.

If you throw exception from catch block which are not thrown by your method, it is meaning less and won't be caught (like in your case).

like image 91
Jivi Avatar answered Mar 26 '23 04:03

Jivi