Skip to content

This package is bad and you should feel bad for using it.

Notifications You must be signed in to change notification settings

kevin-cantwell/exceptions

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This package is bad and you shouldn't use it.

Seriously, don't even read this.

Turn back now.

Still here? Ok cool.

Package exceptions brings the old try/catch/finally pattern you know and love to Go. It's a complete abomination of everything that is holy about Go and if you use it your peers will mock you and your friends will abandon you. Here's how it works:

Try(func() {
fmt.Println("Trying to fish...")
// cause a panic with a Shark
panic(Shark{})
}, Catch(func(cause Fish) {
// gets skipped
fmt.Println("I caught a Fish!")
}), Catch(func(cause Shark) {
// gets called
fmt.Println("I caught a Shark!")
}), Catch(func(cause Swimmer) {
// gets skipped
fmt.Println("I caught a Swimmer!")
}), Finally(func() {
// gets called
fmt.Println("Stopped fishing.")
}))

The above program outputs:

Trying to fish...
I caught a Shark!
Stopped fishing.

Try(func() {
// cause a runtime error
var a []int
fmt.Println(a[2])
}, Catch(func(cause any) {
// will catch anything except nil
fmt.Println("caught:", cause)
}), Finally(func() {
// gets called
fmt.Println("This will print after catching the error.")
}))

The above program outputs:

caught: runtime error: index out of range [2] with length 0
This will print after catching the error.

Try(func() {
// Typically, nil panics are not detected at runtime. But we can detect them if they
// happen in the Try block.
panic(nil)
}, CatchNil(func(cause any) {
fmt.Printf("nil panic! %T\n", cause)
}), Finally(func() {
// gets called
fmt.Println("This will print after catching the error.")
}))

The above program outputs:

nil panic! <nil>
This will print after catching the error.

This follows the semantics of try...catch...finally where any (optional) Finally funcs are invoked directly after Try any Catch that was invoked. The Catch functions take a single arguments: a "cause" of any type. The cause is any type you might expect to be recovered from a panic. Only the first catch that meets these requirements is invoked.

Ironically, this package declares no exception types.

Requires go version 1.18 or greater (for generics)

About

This package is bad and you should feel bad for using it.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages