Exception handling in Gox language defer-recover vs panic and try-catch-finally-GX17

Gox language can use defer and recover mechanisms similar to Go language for exception handling, for example:

defer fn() {
	r = recover()
	if r != nil {
		println("recover:", r)
	}
}()

f, err = os.Open("file.ql")
if err != nil {
	fprintln(os.Stderr, err)
	return 1
}
defer println("exit!")
defer f.Close()

println(10/0)

b = make([]byte, 8)
n, err = f.Read(b)
if err != nil {
	fprintln(os.Stderr, "Read failed:", err)
	return 2
}

println(string(b[:n]))

* Note: Since version 0.988, in order to reduce unnecessary file size, Gox has abandoned other script engines and only supports Qlang engines. Therefore, the content of other script engines in this article is no longer valid and is only reserved for reference to the old version.

In the Anko engine version of the Gox language, compared to the unique exception handling mechanism of the Go language, a more common try-catch-finally combination is introduced.

First of all, there is no defer keyword and recover function in the Gox language, but there is a panic function, which can throw any type of exception, for example:

panic("this is a panic")

panic(123)

panic([1, "good morning", true])

panic({"a": 10, "b": "good morning", "c": true})

These are all possible.

In Gox language, you can use the try-catch-finally combination to catch panic exceptions, including panic generated in Go language functions, and then deal with them accordingly. E.g:


try {
	panic({"a": 10, "b": "good morning", "c": true})
} catch e {
	printfln("error: %v", e)
} finally {
	println("final")
}

try {
	panic(123)
} catch e {
	printfln("error: %v", e)
}

The output after the program runs:

error: map[a:10 b:good morning c:true]
final
error: 123

Shows that these exceptions have been caught correctly.

It can be seen that the exception handling in Gox language is better understood for developers who are used to traditional languages. However, there is currently no defer method. Instead, developers who are familiar with Go programming will find it troublesome. For example, defer is not as convenient as closing open files, closing network connections or database connections.

In fact, finally can be used to replace the role of defer function to a certain extent. In addition, Gox language also supports the use of throw to throw exceptions.

Guess you like

Origin blog.csdn.net/weixin_41462458/article/details/107974927