Go Error Handling

What is Error Handling?

In Go, errors are handled explicitly using return values instead of exceptions.

Functions often return two values: the result and an error.

Loading...
Output:

Returning Errors from Functions

Functions can return an error using the built-in error type.

If no error occurs, return nil.

Loading...
Output:

Checking Errors

Always check if an error is not nil before using the result.

This prevents runtime issues and ensures safe execution.

Loading...
Output:

Ignoring Errors (Not Recommended)

You can ignore errors using the blank identifier _, but this is discouraged.

Ignoring errors can lead to bugs and unexpected behavior.

Loading...
Output:

Creating Custom Errors

You can create custom error messages using fmt.Errorf or errors.New.

This helps provide meaningful feedback when something goes wrong.

Loading...
Output:

Using panic

The panic function stops normal execution of the program.

It should only be used for serious, unexpected errors.

Loading...
Output:

Using recover

The recover function can catch a panic and prevent the program from crashing.

It must be used inside a deferred function.

Loading...
Output:

Real-World Example

Error handling is used in almost every Go program, especially when working with files or APIs.

Loading...
Output:

Why Error Handling is Important

Go encourages explicit error handling to make programs more predictable and reliable.

  • Prevents crashes
  • Makes bugs easier to trace
  • Improves code clarity

Common Mistakes

Be careful with these:

  • Ignoring errors
  • Not checking err != nil
  • Using panic unnecessarily

Practice

Create a function that divides two numbers and returns an error if dividing by zero.

Loading...
Output:

Need Help?