Hi, I have a small piece of C# code and I have a problem to code the double try..catch
in go
c# code:
void IEvent.Event () {
if (itms.Count <= 0) {
ErrorSetCONTINUE();
} else {
MqDumpC dump = itms.Peek();
try {
MqC ftr = SlaveGetFilter();
try {
ProxyForward(ftr, dump);
} catch {
if (++errCnt <= 3) {
ErrorReset();
return;
} else {
throw;
}
}
} catch (Exception ex) {
ErrorCatch (ex);
ErrorWrite();
}
itms.Dequeue();
errCnt = 0;
}
}
go code:
func (this *Filter4) Event() {
if (this.itms.Len() <= 0) {
MqErrorSetCONTINUE()
} else {
dump := this.itms.Front()
defer func() {
if x := recover(); x != nil {
this.ErrorCatch(x)
this.ErrorWrite()
}
this.itms.Remove(dump)
this.errCnt = 0
}()
ftr := this.SlaveGetFilter()
defer func() {
if x := recover(); x != nil {
this.errCnt++
if this.errCnt <= 3 {
this.ErrorReset_0()
return;
} else {
panic(x)
}
}
}()
this.ProxyForward(ftr, dump.Value.(*MqDumpC))
}
}
the problem is that the inner try..catch
doing an return
. This return will skip the first try...catch
in C#.
In go I code the double try...catch
using two defer
. The problem is that the first defer
will always called.
The general problem is:
- the double
defer
code is hard to read - the possible solution always to return the
error
withoutpanic
is difficult to realize because as sender you never know if the receiver is using theerror
.
I would like to use a try...catch
behavior in go
thanks.
+++ addition +++ this is a working solution:
func (this *Filter4) proxyForward(ftr *MqC, dump *list.Element) {
defer func() {
if x := recover(); x != nil {
if _,ok := x.(*MqExceptionC); ok {
this.errCnt++
if this.errCnt <= 3 {
this.ErrorReset_0()
return;
} else {
panic(x)
}
} else {
panic(x)
}
}
}()
this.ProxyForward(ftr, dump.Value.(*MqDumpC))
this.itms.Remove(dump)
this.errCnt = 0
}
func (this *Filter4) Event() {
if (this.itms.Len() <= 0) {
MqErrorSetCONTINUE()
} else {
dump := this.itms.Front()
defer func() {
if x := recover(); x != nil {
this.ErrorCatch(x)
this.ErrorWrite()
this.itms.Remove(dump)
this.errCnt = 0
}
}()
ftr := this.SlaveGetFilter()
this.proxyForward(ftr, dump)
}
}
Problem
- I have double the
this.itms.Remove(dump);this.errCnt = 0
code → not good - the code readability is bad → not good