user12051965
user12051965

Reputation: 147

How to re instantiate variables in try/catch block

I am working on a Cucumber test and I have the following:

        ResponseEntity<OrderGet> createResponse;
        try {
            createResponse = api.createAddress(headers, address);
        } catch (FeignException e) {
            System.out.println(e.status());
            scenarioContext.put("createResponseValidationCode", e.status());
            scenarioContext.put("createResponseValidation", createResponse);
        }

At the last line I get error for Intellij saying that createResponse might have not been initialized. When I initialize it with null and I add an if ( .. != null) it never executes it, it still remains null and does not re instantiate the variable. The line in the try block always throws exception. What approach should I use here?

Upvotes: 0

Views: 254

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103018

Perhaps you don't understand how this code works.

If the catch block executes, that means the try block did not (or did at most partially).

Specifically, if the catch block ends up being involved at all, that means 1 to n of all the statements of the try block have been executed so far, and the last statement executed (which does NOT have to be the last statement in the try block!) did not finish successfully.

Given that there's really only one invoke in your try block (which is invoking the createAddress method), that is the one that DID NOT WORK.

In other words, there is no response object in the first place! - and therefore, it is not possible to send a non-existent response. You have no instance of ResponseEntity. At all. Code failed before we got that far.

If you did this instead:

ResponseEntity<OrderGet> createResponse = null;

... then obviously in the catch block, createResponse would always remain null, and an if (x != null) deal in there would simply mean it would never trigger.

Put in simple terms: It's like this, you ask a baker to bake some bread.

Then the baker tells you: Aw, shoot, mate. I ran out of dough, sorry. You then go: That's no problem. Just give me the bread and I'll tell the client that asked me to get them some bread that this bread could not be baked. At which point the baker goes: You what, mate? I don't have any bread!

Upvotes: 1

Related Questions