0

Ok so here is the scenario from an interview I had recently. It took me a long time, but I still couldn't figure it out. Suppose I have a standard try, catch finally block.

     public int portNumber = 80 ; // not a local variable.



     try {
          portNumber = 80 ;
          functionX() ; //call function x
          .... // some other code might cause an exception
        } 
        catch (Exception e) 
        {
          functionY(portNumber) ; //call function y
        }
        Finally
        {
        }


     public void functionX()
     {
            portNumber = 90 ;
     }

//There is a Thread always call the code above. (the try, catch, finally part)

I have a thread which always keep calling this block of Exception handling, and if the exception happened, I want to retrieve the portNumber when the Exception happened which is 80, not the portNumber currently have, which is 90. How can I do that?

I understand in catch block is something similar to a callback, so when the program execute inside the catch block when port is 80, the thread already called this exception handling block many times, so the port is already 90 or even other numbers. But I still want functionY uses parameter as 80. I tried to use Exception class, which means e.getMessage() etc, I can't find a way to attach port 80 there. How can I make sure functionY(portNumber), the portNumber here is the portNumber when exception happens, in this case 80.

James Xia
  • 173
  • 1
  • 2
  • 9
  • You need to clarify this question, because I have no idea what you are asking. – Elliott Frisch Mar 22 '17 at 21:46
  • http://stackoverflow.com/q/40480/18157 – Jim Garrison Mar 22 '17 at 21:47
  • 1
    `functionX` does NOTHING. Java is pass-by-value. – Jim Garrison Mar 22 '17 at 21:47
  • Sorry about the confusion, I edit here, it's not a question about pass by value vs pass by reference. It's about how to retain the value in Catch Exception block. – James Xia Mar 22 '17 at 21:58
  • Retain what value in catch block? Why would the local value change? You need to be way more specific, and don't just repeat the same words. – Elliott Frisch Mar 22 '17 at 22:07
  • the portNumber is NOT a local variable, so functionX will change the value of portNumber. All I want is to get portNumber 80 inside the catch block. which means if the exception doesn't happen, it gets 90. But when the Thread calls this exception handling again, this time the exception happens, so I want the number 80 instead of 90. Hold on, let me edit the question again, I can't post the whole code here. – James Xia Mar 22 '17 at 22:13

0 Answers0