0
0
Goprogramming~5 mins

Program stability concepts in Go

Choose your learning style9 modes available
Introduction

Program stability means your program keeps working well without crashing or freezing. It helps users trust your software.

When you want your Go program to handle unexpected errors without stopping.
When you need your program to keep running even if some parts fail.
When you want to make sure your program cleans up resources properly before exiting.
When you want to log errors to understand problems without crashing.
When you want to recover from panics to avoid full program crashes.
Syntax
Go
defer func() {
    if r := recover(); r != nil {
        // handle the panic here
    }
}()

// normal code here

defer delays a function call until the surrounding function returns.

recover() catches a panic and lets the program continue.

Examples
This function safely divides two numbers and recovers if division by zero causes a panic.
Go
func safeDivide(a, b int) int {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()
    return a / b
}
Shows how defer runs a statement at the end of the function.
Go
func main() {
    defer fmt.Println("Program ended")
    fmt.Println("Start")
}
Sample Program

This program divides numbers safely. When dividing by zero, it recovers from the panic and continues running.

Go
package main

import "fmt"

func safeDivide(a, b int) int {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()
    return a / b
}

func main() {
    fmt.Println("Result:", safeDivide(10, 2))
    fmt.Println("Result:", safeDivide(10, 0))
    fmt.Println("Program continues after panic")
}
OutputSuccess
Important Notes

Always use recover() inside a deferred function to catch panics.

Use defer to clean up resources like files or network connections.

Program stability improves user experience and helps debugging.

Summary

Program stability means handling errors without crashing.

Use defer and recover() to catch and handle panics.

Stable programs keep running and clean up properly.