CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact
Home Programming Understanding Golang Error Handling

Understanding Golang Error Handling

Rana Ahsan January 18, 2016 Leave a Comment


 Understanding Golang Error Handling    

As golang usually not the first language programmers usually learn, I assume you already have good knowledge in at least other programming language and now expanding your knowledge to golang. If you are just trying to find the error handling mechanism on the official API docs by looking for try/catch mechanism, you probably got tired finding that and may be thinking golang might don’t have any error handling mechanism at all!

Well, Golang doesn’t have support for try/catch, for sure. But, it’s also has its own unique approach for error handling, that no other language has adopted before. It does has a nice and easy to understand ‘errors’ package that you help you to deal with error objects, to handle or create our own error object. For special exception errors, it uses its own unique ‘recover’ mechanism to handle them, which you might need to be using while dealing with sensitive situation like database connectivity, calculate complex mathematical operations that might end up with divide by zero error, or test exception case in writing unit testing in golang etc. You can also generate such situation yourself with ‘panic’ as well. We will see one by one briefly.

Error Handling In Method Call:

First, lets start with how we would know and handle if one of our method invocation has generated some-kind of error or not? In Golang, this approach is somewhat different from other programming language. You will know why later on this article.

[In case you don’t know already: Golang methods can return multiple values at the same time!]

Lets see a simple golang code example snippet that will make it easier to understand better:

returnValue, err := myMethodCall();
if err != nil {
   //do something
}

In case of more than one valid return value, err should be returned as the last return value.

Golang Error Handling Object:

If you are writing a method yourself that requires to return error if something wrong happens in between, use the ‘errors’ package for such purpose. Lets see a small example:

import (
  "errors"
)

func myFunc(i int) (int, error) {

	if i <= 0 {
		return -1, errors.New("value should be greater than zero")
	}

	return i, nil
}

As you can see, if any error occurs, return value is null(or something similar, -1 in this case) and error is set along with a helpful message. On the other hand, if no error occurs, error is set to nil.

Panic/Recover Concept:

As I already mentioned earlier in this post, there is no try catch, golang uses the concept of panic/recover instead. We already seen how we would handle custom error, if occurs inside a method call and how to return such error from methods that we write ourselves. However, these doesn't deal with/can handle unexpected run-time errors that might occur.

Well, why golang is using panic recover instead of try/catch, that's certainly a different discussion. But, in easy words, let me ask you this: how frequently have you seen using try/catch in an existing fair sized project? I believe you have seen a lot. So, here the term 'exception' isn't being really an exceptional case, is it? Also, if we need to return custom error, we are taking help of these exceptions as well. So, basically custom error and runtime errors are all messed up together. Right?

Here, in golang, we are dealing these differently traditionally:

  1. Custom error handling has its own way, as we have seen earlier, by returning error instance besides other return values.
  2. Panic/recover mechanisms are expected to use in truly exceptional cases, and its control flow is different from try/catch in other languages.

Sure, I do recommend you to search on internet a bit more to learn more detailed on 'why'.

So basically, if something very odd/unique exception case has occurred, you will want to do a panic call that will stop the regular flow and causes the process to crash intentionally. And if such case occurs from inside a function and you want to track such situation, you will have to add 'recover' mechanism as a deferred function.

Doing a Panic:

Creating a panic is far easier than its consequences/impact on the code 😉 . Here is a simple panic call:

anOddCondition := true
if anOddCondition {
    panic("I am panicking")
}

Recovering from a panic:

To add the ability to recover from a panic error, either add an anonymous function or define a custom function and call it with 'defer' keyword from inside the method, where panic might be occurring from other internal calls. You don't have to worry about where to place this method specific order call, as it will always be differed at the end of the current method's statements execution completes.

If nothing wrong happens, this call will simply won't have any impact at all. Otherwise, it will catch the error and you can do your custom handling with the error object(logging it etc). A simple recover mechanism code example is given below:

func myMethod() {
         defer func() {
			if err := recover(); err != nil {
				fmt.Println("Error: ", err)
			}
		}()
  //do whatever you want that might generate a panic error
}

Final Words:

Golang team also describes the defer, panic and recover concept in depth in a blog post, which you ready thoroughly as well. If something in this tutorial isn't clear enough, please ask your question by commenting below. Happy coding 🙂

Related

Filed Under: Programming Tagged With: error, golang

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • LinQ Query With Like Operator
  • LinQ To SQL Database Update Operations In C#
  • Get Facebook C# Api Access Token
  • Utilizing Config File In C#.NET Application
  • Control HTML5 Audio With Jquery

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 · Streamline Pro Theme on Genesis Framework · WordPress · Log in