Primrose Docs
  • Home
    • ⛓️Blockchain
      • Avalanche
        • What is AVAX?
      • Ethereum
        • Ethereum Cancun Upgrade Explained(draft)
        • go-ethereum: gas estimate
        • Blockchain Transaction Lifecycle
        • Mempool
        • Gas optimization in Solidity, Ethereum
      • Solidity DeepDive
        • Meta transaction
        • solidity: patterns
        • UUPS vs Transparent
        • Solidity Interface
        • Smart contract storage
        • ERC-2981 Contract
        • Solidity modifier
        • Solidity delete keyword
        • How To Make NFTs with On-Chain Metadata - Hardhat and JavaScript
        • How to Build "Buy Me a Coffee" DeFi dapp
        • How to Develop an NFT Smart Contract (ERC 721) with Alchemy
        • Upgradeable Contract
        • Smart Contract Verification
      • Common
        • Eigenlayer
        • MultiSig(draft)
        • Chain-Based Proof-of- Stake, BFT-Style Proof-of-Stake
        • Byzantine Fault Tolerance
        • Zero-knowledge
        • Hierarchical Deterministic Wallet
        • Maker DAO
        • Defi
        • Uniswap
        • IBC
        • Cosmos
        • Gossip Protocol
        • Tendermint
        • UTXO vs Account
        • Blockchain Layer
        • Consensus Algorithm
        • How does mining work?
        • Immutable Ledger
        • SHA256 Hash
        • Filecoin
        • IPFS - InterPlanetary File System
        • IPFS와 파일코인
        • Livepeer
        • Layer 0
      • Bitcoin
        • BIP for HD Wallet
        • P2WPKH
        • Segwit vs Native Segwit
    • 📖Languages
      • Javascript/Typescript
        • Hoisting
        • This value in Javascript
        • Execution Context
        • About Javscript
        • tsconfig.json
        • Nest js Provider
        • 'return await promise' vs 'return promise'
      • Python
        • Pythonic
        • Python: Iterable, Iterator
        • Uvicorn & Gunicorn
        • WSGI, ASGI
        • Python docstring
        • Decorator in Python
        • Namespace in Python
        • Python Method
      • Go
        • GORM+MySQL Connection Pool
        • Context in golang
        • How to sign Ethereum EIP-1559 transactions using AWS KMS
        • Mongo DB in golang(draft)
        • Golang HTTP Package
        • Panic
        • Golang new/make
        • golang container package
        • errgroup in golang
        • Generic Programming in Golang
        • Goroutine(draft)
    • 📝Database
      • MongoDB in golang
      • Nested loop join, Hash join
      • DB Query plan
      • Index
      • Optimistic Lock Pessimistic Lock
    • 💻Computer Science
      • N+1 query in go
      • Web server 를 구성할 때 Thread, Process 개수를 어떻게 정할 것인가?
      • CAP
      • Socket programming
      • DNS, IP
      • URL, URI
      • TLS과 SSL
      • Caching(draft)
      • Building Microservices: Micro Service 5 Deploy Principle
      • Red Black Tree
      • AOP
      • Distributed Lock
      • VPC
      • Docker
      • All about Session and JWT
      • Closure
      • Singleton Pattern
      • TCP 3 way handshake & 4 way handshake
      • Race Condition
      • Process Address Space 
      • Call by value, Call by reference, Call by assignment
      • Zookeeper, ETCD
      • URL Shortening
      • Raft consensus
      • Sharding, Partitioning
    • 📒ETC
      • K8S SIGTERM
      • SQS
      • Git Branch Strategy: Ship / Show / Ask
      • Kafka
      • Redis Data Types
      • CI/CD
      • How does Google design APIs?
      • Minishell (42 cursus)
      • Coroutine & Subroutine
      • Redis
Powered by GitBook
On this page
  1. Home
  2. Languages
  3. Go

Panic

Panic

Go에서 panic은 예기치 않은 오류가 발생할 때 프로그램의 실행을 중지하는데 사용할 수 있는 내장 함수이다.

프로그램 실행 중 어느 시점에서든 즉시 중지시킬수 있을 것이다.

대부분의 경우에 panic을 사용하는 이유는 디버그 용도, 중대한 결함이 있는 경우, 프로그램 실행 중(bootstrap) 오류와 같다.

중대한 결함이나 네트워크 오류 등이 있는 경우에는 프로그램을 안전하게 지속하는 것 자체가 불가능하므로 panic 상태로 프로그램을 종료하는 것이 나을 수 있다.

Simple example

panic을 사용하는 간단한 예시는 다음과 같다. 0으로 나누는 경우에 panic을 일으킨다.

따라서 다음 fmt.Println절은 실행되지 않을 것이다.

package main

import "fmt"

func divide(a, b int) int {
	if b == 0 {
		panic("divide by zero")
	}

	return a / b
}

func main() {

	fmt.Println("Divide 1 by 0", divide(1, 0))
	fmt.Println("This line will never be printed")
}

Recover

go에서는 panic 이 트리거된 상황에서 recover() 함수를 사용하면 패닉을 중지하고 프로그램을 다시 정상 실행할 수가 있다.

go 런타임은 panic시 deferred function(스택에 쌓인 지연함수)를 실행하기 시작하는데, 보통 다음과 같이 사용한다.

package main

import "fmt"

func connect() error {
	// Attempt to connect to server
	if err != nil {
		panic(err)
	}
	return nil
}

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Recovered from panic:", r)
		}
	}()
	err := connect()
	if err != nil {
		fmt.Println("Error connecting to server:", err)
	}
	// Continue executing program
}
PreviousGolang HTTP PackageNextGolang new/make

Last updated 1 year ago

📖