Back to Predict the Output
Q9Question 9 of 10

What happens when try and finally both have a return?

Key Concepts
  • The finally block's return OVERRIDES the try block's return
  • finally always runs before the method returns – even if try has a return
  • This is a bad practice – never return from a finally block
  • The try's return value is computed but discarded when finally returns
  • Understanding this concept is essential for Java interviews at senior level

Definition

The finally block's return wins. The try's return value is discarded. Never return from finally – it is a code smell.

Execution order:

  1. try block executes, computes return value.
  2. finally block executes (always).
  3. If finally has a return, it overrides try's return.
  4. The method returns finally's value, not try's.

The bank teller prepares a receipt (try return) but the manager intercepts and replaces it (finally return). The customer gets the manager's receipt.

Understanding the Concepts

The code

JAVA
public static int getValue() {
    try {
        return 1;     // computed, but...
    } finally {
        return 2;     // overrides try's return!
    }
}

System.out.println(getValue());  // 2 (not 1!)

Why?

finally always runs before the method returns. If finally has its own return, it replaces whatever try was about to return.

What about exceptions?

JAVA
public static int riskyMethod() {
    try {
        throw new RuntimeException("Error!");
    } finally {
        return 42;  // exception is SWALLOWED! Method returns 42
    }
}
// No exception propagated – silently lost!

A return in finally can swallow exceptions – extremely dangerous.

Rule: NEVER return from finally

JAVA
// BAD
finally { return x; }

// GOOD: finally is for cleanup only
finally { connection.close(); }

What are common mistakes?

A common mistake is assuming the output without tracing through the code step by step.

Wrong approach:

JAVA
package com.bank.quiz;

public class OutputQuiz {
    public static void main(String[] args) {
        // Developers often guess the wrong output
        // because they skip the step-by-step evaluation
        String result = "Balance: " + 100 + 50;
        System.out.println(result);
        // Many guess: "Balance: 150"
        // Actual: "Balance: 10050" (left-to-right string concat)
    }
}

Correct reasoning:

JAVA
package com.bank.quiz;

public class OutputQuiz {
    public static void main(String[] args) {
        // Step 1: "Balance: " + 100 = "Balance: 100" (String + int = String)
        // Step 2: "Balance: 100" + 50 = "Balance: 10050" (String + int = String)
        String result = "Balance: " + 100 + 50;
        System.out.println(result);  // Balance: 10050

        // To get arithmetic: use parentheses
        String correct = "Balance: " + (100 + 50);
        System.out.println(correct);  // Balance: 150
    }
}

Always trace left to right and remember that once a String is involved in concatenation, everything after it becomes string concatenation too.

What should a senior engineer know?

A senior engineer working on banking systems should understand the production implications of this concept.

  • Performance impact. Measure with JMH before making assumptions about which approach is faster.
  • Thread safety. In a multi-threaded banking service processing concurrent transactions, always consider whether the approach is thread-safe.
  • Memory footprint. Use JFR and VisualVM to measure actual memory usage under realistic banking workloads.
  • Monitoring. Set up JMX metrics and alerts for production banking applications.
JAVA
package com.bank.monitoring;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;

public class MemoryMonitor {
    public static void printMemoryUsage() {
        MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
        System.out.println("Heap: " + mem.getHeapMemoryUsage());
        System.out.println("Non-Heap: " + mem.getNonHeapMemoryUsage());
    }
}

What are the edge cases?

Edge cases can cause unexpected behavior in banking applications. Here are some to watch for.

JAVA
package com.bank.edge;

public class EdgeCaseDemo {
    public static void main(String[] args) {
        // Edge case 1: null handling
        String accountId = null;
        try {
            System.out.println(accountId.length());
        } catch (NullPointerException e) {
            System.out.println("Null account ID");
        }

        // Edge case 2: empty vs null
        String emptyId = "";
        System.out.println(emptyId.isEmpty());  // true
        System.out.println(emptyId == null);     // false

        // Edge case 3: boundary values
        java.math.BigDecimal zero = java.math.BigDecimal.ZERO;
        java.math.BigDecimal negativeBalance = new java.math.BigDecimal("-0.01");
        System.out.println(zero.compareTo(negativeBalance) > 0);  // true
    }
}
TEXT
Null account ID
true
false
true

Always test with null values, empty strings, boundary values, and negative amounts in banking applications.

What are common interview follow-up questions?

Interviewers often follow up with these related questions:

  • How does this concept apply to a high-throughput banking transaction system?
  • What are the performance implications in a production environment?
  • How would you debug issues related to this concept?
  • What tools would you use to monitor this in production?
  • How does this behave differently in Java 8 vs Java 17+?

When answering follow-up questions, always relate your answer back to practical experience. For example, at National Bank of India, Rajesh debugged a production issue related to this concept by using JFR recordings and heap dumps. Providing concrete examples from banking systems shows the interviewer that you understand both the theory and the practice.

Visual Overview

DIAGRAM
  try { return 1; } finally { return 2; }
  → try computes 1
  → finally runs, returns 2 (overrides)
  → method returns 2

  try { throw e; } finally { return 42; }
  → exception thrown
  → finally returns 42 (exception swallowed!)
  → method returns 42, exception lost

  Rule: NEVER return from finally

Key Takeaway

When both try and finally have a return, finally's return wins and try's is discarded. A return in finally can also swallow exceptions silently. Never return from a finally block.

One sentence to remember: finally's return overrides try's return – never return from finally.

---

Share
Use ← → arrow keys to navigate