In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use GE language exception mechanism to simulate TryCatch exception catch". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use go language exception mechanism to simulate TryCatch exception catch".
No matter what the exception handling mechanism is, the core principle is the same. generally speaking, a perfect exception handling mechanism needs to be composed of the following three parts.
Throw an exception
Code snippet that handles exceptions
Get exception information
Let's first use Java's exception handling mechanism to illustrate this point.
Import java.io.IOException
Public class Main {
Public static void main (String [] args) {
Try
{
Boolean ioException = false
If (ioException) {
Throw new IOException ("ioexception")
} else {
Throw new Exception ("exception")
}
}
Catch (IOException e) {
System.err.println (e)
}
Catch (Exception e) {
System.out.println (e)
}
Finally
{
System.out.println ("finally")
}
}
}
The above code is the standard Java exception handling mechanism, the throw in the try part is used to throw the exception, and the code snippet in the catch part is used to handle the specific exception, and the exception information can be obtained through the parameter e of the catch clause. So for Java, the above three extremely important components all have.
For the GE language, panic, defer and recover also correspond to these three parts. Where panic is a function that throws an exception, which is equivalent to the throw function in Java. Defer is a keyword that modifies functions, and functions decorated with defer are called automatically when an exception is thrown. Recover is a function used to get exception information, usually used in functions decorated with defer.
The following is a piece of code that handles exceptions in the go language.
Package main
Import "fmt"
Func main () {
/ / functions that handle exceptions
Defer func () {
Fmt.Println ("start handling exceptions")
/ / get exception information
If err:=recover (); erratically responsible nil {
/ / output exception information
Fmt.Println ("error:", err)
}
Fmt.Println ("end exception handling")
} ()
ExceptionFun ()
}
Func exceptionFun () {
Fmt.Println ("exceptionFun starts execution")
Panic ("exception message")
Fmt.Println ("end of exceptionFun execution")
}
Implement Go version of TryCatch
Now that you understand the exception handling mechanism of the Go language, then use the exception handling mechanism to simulate the try...catch...finally statement.
Now let's analyze if the simulation. The simulation process needs to complete the following work.
Try, catch, and finally all have their own code snippets, so in order to simulate try...catch...finally, you need to use three Go functions to simulate the code snippets of try, catch, and finally, respectively. The three Go functions are Try, Catch, and Finally.
To determine where these three functions are called. Try is normally executed code, so call the Try function first. The Catch function is called only when an exception is thrown, so it should be called in the function decorated with defer, and the exception information needs to be obtained in the Catch function, so the Catch function should be called after using the cover function to obtain the exception information. Usually, the exception information will be passed directly to the Catch function as a parameter. The Finally function must be called regardless of whether an exception is thrown, so the Finally function should be decorated with defer, and it is the first function to be decorated with defer. In this way, the Finally function must be called back just before the end of the current function.
Trigger an exception, which is very simple, just use the panic function.
The basic principle of using the exception handling mechanism of the go language to simulate try...catch...finally statements is clearly described above, and the complete implementation code is given below.
Package main
Import (
"fmt"
)
Type ExceptionStruct struct {
Try func ()
Catch func (Exception)
Finally func ()
}
Type Exception interface {}
Func Throw (up Exception) {
Panic (up)
}
Func (this ExceptionStruct) Do () {
If this.Finally! = nil {
Defer this.Finally ()
}
If this.Catch! = nil {
Defer func () {
If e: = recover (); e! = nil {
This.Catch (e)
}
} ()
}
This.Try ()
}
Func main () {
Fmt.Println ("start execution...")
ExceptionStruct {
Try: func () {
Fmt.Println ("try...")
Throw ("error occurred")
}
Catch: func (e Exception) {
Fmt.Printf ("exception% v\ n", e)
}
Finally: func () {
Fmt.Println ("Finally...")
}
}. Do ()
Fmt.Println ("end running")
}
The above code encapsulates the Try, Catch, and Finally functions in the ExceptionStruct structure. Then the invocation method is consistent with the previous description. Executing this code will output the information shown in the following figure.
Image.png
Enhanced version of TryCatch
So far, the try...catch...finally statement has actually been fully implemented, but careful students will find that there is a slight problem with this implementation. Usually, there is only one try...catch...finally statement in the try part, the finally part is optional, but there can be at most one, and the catch part is optional, which can have 0 to n, that is, the catch part can have as many as you want. But in the previous implementation, the Catch function can only specify one, so what should I do if I want to specify as many as possible? In fact, it is very simple, with a collection of Catch functions to save all the specified Catch functions. However, you need to quickly locate a Catch function. In Java, we locate a specific catch clause through exception types (such as IOException, Exception, etc.). We can also simulate this process by locating the Catch function corresponding to the exception through a specific exception. For convenience, we can use the exception code of int type. Then before calling the Catch function, you need to locate a Catch function through the exception code and then call it. Here is the complete implementation code.
Package main
Import (
"log"
)
Type Exception struct {
Id int / / exception id
Msg string / / exception msg
}
Type TryStruct struct {
Catches map[int] ExceptionHandler
Try func ()
}
Func Try (tryHandler func ()) * TryStruct {
TryStruct: = TryStruct {
Catches: make (map [int] ExceptionHandler)
Try: tryHandler
}
Return & tryStruct
}
Type ExceptionHandler func (Exception)
Func (this * TryStruct) Catch (exceptionId int, catch func (Exception)) * TryStruct {
This.catches [exceptionId] = catch
Return this
}
Func (this * TryStruct) Finally (finally func ()) {
Defer func () {
If e: = recover (); nil! = e {
Exception: = e (Exception)
If catch, ok: = this.catches [exception.Id]; ok {
Catch (exception)
}
Finally ()
}
} ()
This.try ()
}
Func Throw (id int, msg string) Exception {
Panic (Exception {id,msg})
}
Func main () {
Exception.Try (func () {
Log.Println ("try...")
/ / specified exception code as 2 and error message as error2
Exception.Throw (2, "error2")
) .catch (1, func (e exception.Exception) {
Log.Println (e.IDMAE. MSG)
) .catch (2, func (e exception.Exception) {
Log.Println (e.IDMAE. MSG)
}) .Finally (func () {
Log.Println ("finally")
})
}
The execution result is shown in the following figure.
Image.png
The only difference between this implementation and try...catch...finally in Java is that the Finally function must be called because the code that handles the exception is in the Finally function. However, this does not affect the use, if there is nothing to deal with in the finally section, then set an empty function.
For your convenience, I have encapsulated the implementation into a function library with the call code as follows:
Package main
Import (
"exception"
"log"
)
Func main () {
Exception.Try (func () {
Log.Println ("try...")
Exception.Throw (2, "error2")
) .catch (1, func (e exception.Exception) {
Log.Println (e.IDMAE. MSG)
) .catch (2, func (e exception.Exception) {
Log.Println (e.IDMAE. MSG)
}) .Finally (func () {
Log.Println ("finally")
})
}
Thank you for your reading. The above is the content of "how to simulate TryCatch exception capture with GE language exception mechanism". After the study of this article, I believe you have a deeper understanding of how to use go language exception mechanism to simulate TryCatch exception catch, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.