How to exit from the main function in Golang

Last updated on Sep 9, 2022 by Suraj Sharma



In this tutorial, you will learn how you can quit/exit from the main program when an error occurs inside the main function in Golang


To exit from the main program in Golang


Exit() function of the os module is used to stop the main function from completely executing if an error occurs inside the main function.

Moreover, if the exit is because of an error we pass a non-zero status code as an argument to the Exit function otherwise, pass zero as a status code.


Example


package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    // this returns an error
    _, err := strconv.Atoi("hello")
    if err != nil {
        fmt.Printf("error occured %s", err.Error())
        os.Exit(1)
    }
}

**OUTPUT**

error occured strconv.Atoi: parsing "hello": invalid syntax
Process finished with exit code 1


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.