Defer, Panic & Recover Questions with Answers

11 practice questions on Defer, Panic & Recover (Go) with answers and step-by-step solutions. Try 10 samples below, then practise all 11 free in the AptiNest app.

Sample questions

Question 1Easy

When does a deferred function call run?

  1. At program exit only, after main returns and before the operating system reclaims memory
  2. When the garbage collector runs
  3. Immediately
  4. When the surrounding function returns

Answer: D. When the surrounding function returns

Explanation

defer schedules cleanup such as closing files to run as the function exits, even on panic.

Step-by-step solution

  1. Deferred functions run when the surrounding function returns.
  2. This ensures resources are cleaned up properly before the function ends.
  3. It happens regardless of whether the function exits normally or via panic.
  4. The deferred call is executed after the function's normal return value is computed.
  5. This makes it ideal for tasks like closing files or releasing locks.

Why the other options are wrong

  • A. Deferred calls do not wait for program exit; they run when their own function returns.
  • B. The garbage collector does not trigger defers; they run when the function ends.
  • C. Defers do not run immediately; they are queued until the function returns.

Tip: Use defer to handle cleanup tasks automatically when a function finishes.

Question 2Easy

What is the output?

package main

import "fmt"

func main() {
	defer fmt.Print("1 ")
	defer fmt.Print("2 ")
	defer fmt.Print("3 ")
	fmt.Print("start ")
}
  1. 3 2 1 start
  2. start 3 2 1
  3. start 1 2 3
  4. 1 2 3 start

Answer: B. start 3 2 1

Explanation

Deferred calls run in last-in, first-out order after the function body finishes.

Step-by-step solution

  1. The three defer lines are scheduled, not run, when main starts.
  2. fmt.Print('start ') runs in the body, so 'start ' is printed first.
  3. At return the deferred calls run last in, first out: '3 ', then '2 ', then '1 '.
  4. Output: start 3 2 1, so the answer is option B.

Why the other options are wrong

  • A. Deferred calls run after the body, so 'start' always comes first.
  • C. Defers run in reverse order, so 3 comes before 1.
  • D. The body prints 'start' before the deferred calls run, so it cannot come last.

Tip: Defers run at function return in reverse order; body prints happen before any deferred call.

Question 3Easy

Why is defer f.Close() written right after a successful os.Open?

  1. It speeds up reading
  2. It makes the file read-only
  3. So the file is closed on every return path, including errors later
  4. Close must be scheduled before the first read, or the read returns an error immediately

Answer: C. So the file is closed on every return path, including errors later

Explanation

Placing cleanup next to acquisition prevents leaks when later code returns early.

Step-by-step solution

  1. Defer schedules Close to run when the function returns.
  2. Placing it right after a successful os.Open means every later return, including error returns, still closes the file.
  3. So the reason is that the file is closed on every return path, which is option C.

Why the other options are wrong

  • A. Defer does not speed up reading; it only schedules the close.
  • B. Close does not change the file's permissions.
  • D. Close runs at return, not before the read, so the read is not affected.

Tip: Pair each successful acquire with a defer release right away.

Question 4Medium

When is panic appropriate in idiomatic Go?

  1. To return multiple values
  2. To exit loops
  3. For every error, instead of returning error values, since panics are cheaper to handle
  4. For truly unrecoverable programmer errors, not for expected failures

Answer: D. For truly unrecoverable programmer errors, not for expected failures

Explanation

Expected conditions like file-not-found are returned as errors; panic signals bugs or impossible states.

Step-by-step solution

  1. Panic is used for unexpected issues, not routine errors.
  2. Errors are for recoverable problems like missing files.
  3. Panics indicate serious bugs in code logic.
  4. Recoverable failures should use error returns instead.
  5. Unrecoverable programmer mistakes trigger panics.
  6. Final answer: For truly unrecoverable programmer errors, not for expected failures.

Why the other options are wrong

  • A. Multiple return values are a normal Go feature; panic is not used to return them.
  • B. Loops are exited with break or return; panic is not a way to leave a loop.
  • C. Panics are costly to handle, and expected failures should return errors, not panic.

Tip: Use panic for bugs, not for normal error handling.

Question 5Medium

What is the output?

package main

import "fmt"

func main() {
	x := 1
	defer fmt.Println(x)
	x = 2
}
  1. Compile error
  2. 2
  3. 1
  4. 0

Answer: C. 1

Explanation

Arguments to a deferred call are evaluated when the defer statement runs, not when the call executes.

Step-by-step solution

  1. Defer evaluates its arguments when the defer line runs, not when the deferred call runs.
  2. At the defer line x is 1, so the deferred call holds the value 1.
  3. x = 2 changes x later, but the deferred call still prints the saved 1.
  4. Output is 1, so the answer is option C.

Why the other options are wrong

  • A. The code compiles; x is an int and Println accepts it.
  • B. The value 2 is assigned after the defer line, so the saved argument is still 1.
  • D. X is 1 when the defer is set up, so the output is never 0.

Tip: Arguments to defer are evaluated immediately; only the call itself is postponed.

Question 6Medium

What is the output?

package main

import "fmt"

func safe() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Print("recovered: ", r, " ")
		}
	}()
	panic("oops")
}

func main() {
	safe()
	fmt.Println("after")
}
  1. recovered: oops
  2. recovered: oops after
  3. after
  4. Runtime panic: oops

Answer: B. recovered: oops after

Explanation

recover inside a deferred function stops the panic; safe returns normally and main continues.

Step-by-step solution

  1. panic('oops') runs deferred functions.
  2. The deferred func recovers and prints 'recovered: oops ' with a trailing space.
  3. safe returns normally, so main prints 'after'.

Why the other options are wrong

  • A. main continues and also prints after.
  • C. The recovered message prints before after.
  • D. recover stops the panic.

Question 7Medium

What is the output?

package main

import "fmt"

func main() {
	for i := 0; i < 3; i++ {
		defer fmt.Print(i, " ")
	}
	fmt.Print("x ")
}
  1. 2 1 0 x
  2. x 2 1 0
  3. x 0 1 2
  4. x 3 3 3

Answer: B. x 2 1 0

Explanation

Each defer captures the current i as an argument; they run LIFO after main's body.

Step-by-step solution

  1. The loop schedules three deferred Print calls with i = 0, 1 and 2.
  2. fmt.Print('x ') runs in the body first, printing 'x '.
  3. Deferred calls run in reverse: i = 2, then 1, then 0, giving '2 1 0 '.
  4. Output is x 2 1 0, so the answer is option B.

Why the other options are wrong

  • A. The body's 'x ' prints before the deferred calls, so x comes first.
  • C. Deferred calls run last in, first out, so 2 comes before 0.
  • D. Each defer captures its own i (0, 1, 2), so the values are not all 3.

Tip: Deferred calls run in reverse order after the body; each argument is fixed when its defer runs.

Question 8Hard

Why can defer inside a long loop be a problem?

  1. It causes a compile error after 100 iterations
  2. Deferred calls pile up until the function returns, holding resources
  3. Each defer runs immediately in loops
  4. defer is not allowed inside loops, so the code fails to compile with a 'defer in loop' error

Answer: B. Deferred calls pile up until the function returns, holding resources

Explanation

Opening thousands of files in a loop with defer Close keeps them all open; move the body into a helper function.

Step-by-step solution

  1. Defer adds functions to a stack, not running them immediately.
  2. Each defer call is stored until the surrounding function exits.
  3. This can lead to many deferred calls holding resources.
  4. Deferred calls are executed in reverse order when the function returns.
  5. So, defer inside loops can cause resource leaks.

Why the other options are wrong

  • A. Defer in a loop is legal, so there is no compile error after 100 iterations.
  • C. Deferred calls wait until the function returns, not on each iteration.
  • D. defer is legal inside loops, so no defer-in-loop compile error exists.

Tip: Use defer carefully in loops; consider helper functions for resource management.

Question 9Hard

A goroutine panics and nothing in that goroutine recovers. What happens?

  1. The whole program crashes
  2. Only that goroutine stops; others continue
  3. The panic is logged and ignored
  4. main recovers it automatically

Answer: A. The whole program crashes

Explanation

A recover in main cannot catch a panic from another goroutine; each goroutine must handle its own.

Step-by-step solution

  1. A panic unwinds the goroutine it happened in.
  2. If no code in that goroutine recovers it, the runtime stops the whole program.
  3. Other goroutines do not keep the program alive after an unrecovered panic.
  4. So the whole program crashes, which is option A.

Why the other options are wrong

  • B. An unrecovered panic in any goroutine terminates the entire process.
  • C. Go does not log and ignore panics; it crashes the program.
  • D. Main does not recover panics from other goroutines; recover needs an explicit deferred call.

Tip: A panic in any goroutine is fatal unless that goroutine recovers it.

Question 10Hard

What is the output?

package main

import "fmt"

func f() (n int) {
	defer func() { n *= 2 }()
	return 5
}

func main() {
	fmt.Println(f())
}
  1. 5
  2. 0
  3. Compile error
  4. 10

Answer: D. 10

Explanation

return 5 sets the named result n to 5, then the deferred closure doubles it before the function actually returns.

Step-by-step solution

  1. The function f() returns 5 and assigns it to n.
  2. Deferred func() { n *= 2 } doubles n to 10.
  3. fmt.Println(f()) prints the final value of n.
  4. N is 10 after the deferred call runs.
  5. Final answer: 10.

Why the other options are wrong

  • A. Returning 5 is not the final value, because the deferred call changes the named result n.
  • B. The result is not 0; the return sets n to 5 before the defer runs.
  • C. The code compiles: n is a named result, so the defer can change it and the return is valid.

Tip: Remember deferred calls modify the return value after it's set.

Practise all 11 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Go topics · All topics