DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Bitwise Operators in Go
  • Leveraging Golang for Modern ETL Pipelines
  • Golang: Is It a Memory Leak?

Trending

  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • Cosmos DB Disaster Recovery: Multi-Region Write Pitfalls and How to Evade Them
  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  • The Role of AI in Identity and Access Management for Organizations

Try and Catch in Golang

The author compares talks about exception handling in Java, the absence of exception handling in Go, and a way to mimic it.

By 
Peter Verhas user avatar
Peter Verhas
DZone Core CORE ·
May. 30, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
105.7K Views

Join the DZone community and get the full member experience.

Join For Free

Golang (as opposed to Java) does not have exceptions such as try/catch/finally blocks. It has strict error handling with functions called panic and recover and a statement named defer. It is a totally different approach. Is this a better approach than Java takes? (Sorry that I keep comparing it to Java. I am coming from the Java world.)

When we handle exceptions in Java we enclose the commands into a ‘try’ block denoting that something may happen that we want to handle later in a ‘catch’ block. Then we have the ‘finally’ block that contains all the things that are to be executed no matter what. The problem with this approach is that it separates the commands that belong to the same concern.

Image title

We want to deal with some file. So we open a file and later, no matter what, we want to close it. When the programmer writes the finally block the file opening is far away somewhere at the start of the method. To remember all the things that we have to do to clean up the actions at the start of the method you have to scroll up to the start of the method where the ‘try’ block starts.

Okay, I know that your method is too long if you have to scroll back. Your methods follow clean code principles and are not longer than ten lines each (including JavaDoc). Even though the issue is still there, it is formulated according to the order of execution expected and not according to the order the logic dictates. The logic says the following: if I open a file, I will want to close it. If I allocate some resource I will want to release it. It is better keeping these concerns together. We are not programming in Assembly, where you write the mnemonics in the strict order of execution. We define the algorithmic solution in a high-level language and the compiler will generate the Assembly. Real work has to be done by the brain, mechanical work is for the CPU. These days we have CPUs.

Golang has the command ‘defer’ for this purpose. You open a file and you mention on the next line that you will want it to be closed some time calling the function you provide. This is the much better approach, which the developers of the Java language also know hence the introduction of the interface ‘closeable’ and try-with-resources statement.

Still, programmers coming from the Java world being introduced to Go are longing for exception handling. If you really want you can mimic it in Go. It will not be the same and I do not really think one should take something that is good and instead use something old and mediocre, but you can write

Block{
        Try: func() {
            fmt.Println("I tried")
            Throw("Oh,...sh...")
        },
        Catch: func(e Exception) {
            fmt.Printf("Caught %v\n", e)
        },
        Finally: func() {
            fmt.Println("Finally...")
        },
    }.Do()

Homework: find out the sample code that is before these lines (Go constructs) that make this possible. Solution is here: https://play.golang.org/p/LXroobH8SM.

package main
 
import (
    "fmt"
)
 
type Block struct {
    Try     func()
    Catch   func(Exception)
    Finally func()
}
 
type Exception interface{}
 
func Throw(up Exception) {
    panic(up)
}
 
func (tcf Block) Do() {
    if tcf.Finally != nil {
 
        defer tcf.Finally()
    }
    if tcf.Catch != nil {
        defer func() {
            if r := recover(); r != nil {
                tcf.Catch(r)
            }
        }()
    }
    tcf.Try()
}
 
func main() {
    fmt.Println("We started")
    Block{
        Try: func() {
            fmt.Println("I tried")
            Throw("Oh,...sh...")
        },
        Catch: func(e Exception) {
            fmt.Printf("Caught %v\n", e)
        },
        Finally: func() {
            fmt.Println("Finally...")
        },
    }.Do()
    fmt.Println("We went on")
}

See also a recent similar solution at http://hackthology.com/exceptions-for-go-as-a-library.html from Tim Henderson.

Golang

Published at DZone with permission of Peter Verhas, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Bitwise Operators in Go
  • Leveraging Golang for Modern ETL Pipelines
  • Golang: Is It a Memory Leak?

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: