Panic behavior in Go - Time & Space Complexity
When we look at panic behavior in Go, we want to understand how it affects the running time of a program.
Specifically, we ask: How does panicking change the number of steps the program takes?
Analyze the time complexity of the following code snippet.
func process(items []int) {
for _, item := range items {
if item == 0 {
panic("zero found")
}
// some processing
}
}
This code loops through a list and panics if it finds a zero, stopping the program immediately.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of items.
- How many times: Up to the first zero found or all items if no zero.
Execution grows with the number of items until a zero is found.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 steps or fewer if zero found early |
| 100 | Up to 100 steps or fewer if zero found early |
| 1000 | Up to 1000 steps or fewer if zero found early |
Pattern observation: The program stops early if a zero is found, so the work can be less than the input size.
Time Complexity: O(n)
This means the program's running time grows linearly with the number of items, but it may stop sooner if a panic occurs.
[X] Wrong: "Panic makes the program run slower for all items always."
[OK] Correct: Panic stops the program immediately, so it can actually reduce the work done, not increase it for all items.
Understanding panic behavior helps you explain how error handling affects program flow and performance in real situations.
"What if we replaced panic with returning an error? How would the time complexity change?"
Practice
panic is called in a Go program?Solution
Step 1: Understand panic behavior
In Go, callingpanicimmediately stops normal execution and begins panicking.Step 2: Effect on program flow
The program prints a stack trace and error message, then terminates unless recovered.Final Answer:
The program stops immediately and prints an error message. -> Option CQuick Check:
Panic stops program = B [OK]
- Thinking panic allows program to continue
- Confusing panic with error return
- Assuming panic restarts the program
Solution
Step 1: Recall panic syntax
Panic is a built-in function called with parentheses and a string argument.Step 2: Check each option
panic("error occurred") uses correct function call syntax. Others have invalid assignment, colon, or extra semicolon.Final Answer:
panic("error occurred") -> Option BQuick Check:
Panic is a function call = D [OK]
- Using assignment instead of function call
- Adding extra semicolons inside panic call
- Using colon instead of parentheses
package main
import "fmt"
func main() {
fmt.Println("Start")
panic("something went wrong")
fmt.Println("End")
}Solution
Step 1: Trace program execution
The program prints "Start" first, then calls panic with a message.Step 2: Effect of panic on following code
After panic, the program stops immediately, so "End" is not printed. Panic message and stack trace appear.Final Answer:
Start something went wrong panic stack trace -> Option DQuick Check:
Panic stops after printing Start = C [OK]
- Expecting code after panic to run
- Ignoring panic message output
- Confusing panic output with normal print
func divide(a, b int) int {
if b == 0 {
panic("division by zero")
}
return a / b
}
func main() {
result := divide(10, 0)
fmt.Println(result)
}Solution
Step 1: Check code for syntax errors
The code usesfmt.Printlnbut does not import "fmt" package.Step 2: Validate panic usage
Panic is allowed inside functions; division by zero should panic to avoid runtime error.Final Answer:
Missing import of "fmt" package -> Option AQuick Check:
Missing import causes compile error = A [OK]
- Thinking panic is not allowed in functions
- Ignoring missing imports
- Assuming division by zero returns zero
func safeDivide(a, b int) int {
// Your code here
}
func main() {
fmt.Println(safeDivide(10, 0))
}Solution
Step 1: Understand panic and recover usage
Recover must be called inside a deferred function to catch panic and prevent program crash.Step 2: Analyze each option
func safeDivide(a, b int) int { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic") } }() if b == 0 { panic("division by zero") } return a / b } uses defer with recover to catch panic and prints a message, then continues. It returns the division result or panics if divisor is zero. func safeDivide(a, b int) int { defer func() { if r := recover(); r != nil { return 0 } }() if b == 0 { panic("division by zero") } return a / b } tries to return inside defer, which does not affect the outer function's return. func safeDivide(a, b int) int { if b == 0 { panic("division by zero") } return a / b } panics without recovery. func safeDivide(a, b int) int { if b == 0 { return 0 } return a / b } returns 0 without panic.Final Answer:
Option A correctly uses panic and recover to handle error and avoid crash. -> Option AQuick Check:
Defer recover catches panic = A [OK]
- Returning inside defer does not change function return
- Not using recover causes program crash
- Ignoring panic and returning zero silently
Ready to prove it?
Pass the test and this pattern moves unknown
