Created
April 30, 2021 15:01
-
-
Save StevenBlack/d7c2745aa24f348e2773c8067485dc9c to your computer and use it in GitHub Desktop.
Go Try/Catch/Finally implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// source: 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") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment