0
0
Goprogramming~30 mins

Panic behavior in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Panic behavior
📖 Scenario: Imagine you are writing a simple Go program that processes user input. Sometimes, the input might cause unexpected errors. Go uses panic to stop the program immediately when something goes wrong.
🎯 Goal: You will create a Go program that demonstrates how panic works by intentionally causing a panic and then recovering from it using defer and recover.
📋 What You'll Learn
Create a function called causePanic that triggers a panic with the message "Something went wrong!".
Create a function called handlePanic that uses defer and recover to catch the panic and print "Recovered from panic: " followed by the panic message.
Call handlePanic and then causePanic inside the main function.
Print "Program continues after panic recovery." after calling causePanic.
💡 Why This Matters
🌍 Real World
In real Go programs, panic and recover help handle unexpected errors like file read failures or invalid data, allowing programs to clean up and continue safely.
💼 Career
Understanding panic behavior is important for Go developers to write robust, fault-tolerant applications that can handle errors without crashing unexpectedly.
Progress0 / 4 steps
1
Create the causePanic function
Write a function called causePanic that triggers a panic with the message "Something went wrong!" using panic("Something went wrong!").
Go
Hint

Use the panic function inside causePanic to stop the program with the given message.

2
Create the handlePanic function with defer and recover
Write a function called handlePanic that uses defer to call an anonymous function. Inside the anonymous function, use recover() to catch the panic. If a panic is caught, print "Recovered from panic: " followed by the panic message using println.
Go
Hint

Use defer to delay the anonymous function until handlePanic returns. Inside it, use recover() to catch the panic value.

3
Call handlePanic and causePanic inside main
Inside the main function, first call handlePanic() and then call causePanic().
Go
Hint

Call handlePanic() before causePanic() in main to catch the panic.

4
Print a message after panic recovery
After calling causePanic() in main, add a println statement that prints "Program continues after panic recovery.".
Go
Hint

Use println("Program continues after panic recovery.") after causePanic() in main.