-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.go
60 lines (50 loc) · 1.31 KB
/
logging.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Understanding the differences between fmt.Print, log.Fatal, and panic:
// - fmt.Print: prints and continues execution
// - log.Fatal: prints and exits the program
// - panic: prints a panic message and begins unwinding the stack, runs deferred functions and then terminates
package main
import (
"fmt"
"log"
"os"
)
// Function demonstrating log.Fatal
func readFile(filename string) (string, error) {
fmt.Println("Reading data from:", filename)
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
var content string
_, err = fmt.Fscan(file, &content)
if err != nil {
return "", err
}
return content, nil
}
// Function demonstrating panic
func checkConfig() {
// Recover from panic
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
fmt.Println("Checking configuration file...")
if _, err := os.Stat("config.json"); os.IsNotExist(err) {
panic("Config file is missing") // Trigger panic if config file doesn't exist
}
}
// Main function demonstrating the three scenarios
func main() {
// Scenario 1: Panic
checkConfig()
// Scenario 2: Log.Fatal
content, err := readFile("input.txt")
if err != nil {
log.Fatal("Error reading file:", err)
}
// Scenario 3: fmt.Print
fmt.Println("Successfully read file content:", content)
}