Error Handling in Go
# CHAPTER 16
Error Handling in Go
1. Introduction
If you are coming from Python, Java, or C#, you are used to wrapping dangerous code in atry/catch block. If something explodes, the program jumps to the catch block.
Go does NOT have try/catch exceptions. Go believes that errors are a normal part of programming, not magical exceptions. In Go, errors are treated as normal values. Functions return errors, and you explicitly check them using if err != nil.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Understand the
errorinterface.
- Check and handle returned errors properly.
-
Create custom errors using
errors.New().
-
Format detailed errors using
fmt.Errorf().
-
Understand
panicandrecover.
3. The error Interface
In Go, error is a built-in interface that has a single method: Error() string. If a function might fail, you design it to return multiple values: the result, AND an error.
If the operation succeeds, the error returned is nil.
If it fails, it returns an error object containing a message.
4. Checking Errors (if err != nil)
Let's simulate parsing a string into an integer. The strconv package can fail if the string contains letters.
*Note: You will write if err != nil hundreds of times in Go. It forces you to think about failure at every step.*
5. Creating Custom Errors
You can generate your own errors using theerrors package.
6. Formatting Detailed Errors
Often, a generic error isn't enough. You want to include variable data in the error message. Usefmt.Errorf(), which acts just like Printf, but generates an error object instead of printing to the console.
7. Panic and Recover
If Go doesn't have exceptions, what happens if the program actually crashes (like dividing by zero, or accessing an out-of-bounds array)? This is called a Panic. A panic immediately stops execution and kills the program.You can trigger a panic manually for completely unrecoverable situations (e.g., the server failed to start because the port is in use).
Recover:
If a Panic happens, you can catch it and prevent the application from crashing using recover() inside a defer statement. *(Note: defer executes a function at the very end, right before the surrounding function exits).*
8. Common Mistakes
-
Ignoring Errors using
:price, := strconv.Atoi("abc"). If it fails,pricebecomes0and you never know why. Never ignore errors in production code.
-
Overusing Panic: Beginners use
paniclikethrow Exceptionin Java. In Go,panicis strictly for catastrophic, unrecoverable crashes. For normal logic flow (bad password, missing file), always return anerror.
9. Best Practices
-
Error messages should be completely lowercase and should not end with punctuation. Go's standard libraries follow this to allow errors to be easily chained together. (e.g.,
errors.New("user not found")rather than"User not found!").
10. Exercises
-
1.
Write a function
checkPasswordLength(pwd string) error.
-
2.
If the length is less than 8, return an error using
fmt.Errorf.
-
3.
Test it in
mainand print the result.
11. MCQs with Answers & Explanations
Q1. Does Go use try/catch exception blocks?
a) Yes b) No
Answer: b) No. *Explanation: Go returns errors as normal values.*
What is the standard way to check if an operation failed in Go?
If a function succeeds, what value should the error return be?
Which package allows you to create a simple, basic error?
Which function is used to create an error containing formatted variables (like %d)?
What is a Panic in Go?
panic() for minor logic errors like a bad password?
a) Yes b) No, you should return a standard error instead.
Answer: b) No, you should return a standard error.
Which keyword guarantees a function will run at the very end of the current function, even if a panic occurs?
Which function can catch a panic and prevent the program from crashing?
_ to ignore the error completely
Answer: b) Using the blank identifier to ignore the error.
12. Interview Preparation
Interview Questions:-
1.
Why did the Go creators choose to use explicit error checking (
if err != nil) overtry/catchexceptions?
-
2.
Explain the difference between returning an
errorand triggering apanic.
-
3.
How do
defer,panic, andrecoverwork together?
13. Summary
Go's error handling forces developers to confront failure directly. By treating errors as normal return values, the execution flow remains incredibly easy to trace. Whileif err != nil requires extra typing, it results in highly robust, predictable, and crash-resistant backend applications.