Python代码在try except块中崩溃

3

我正在使用云平台运行程序,当程序在try/except块中遇到错误时会崩溃。我不知道是不是由于平台的问题,但我需要一种方法来避免程序崩溃。

try:

    r = self.http.request('GET', 'https://www.alphavantage.co/query?function=TIME_SERIES_INTADAY&symbol=VIX&interval=1min&apikey=apikey')
    data = json.loads(r.data)

    if 'Time Series (1min)' in data.keys():
        self.VIX = Decimal(data['Time Series (1min)'][list(data['Time Series (1min)'].keys())[0]]['4. close'])
    else:  
        raise Exception("key")


except Exception as e:

    self.Debug('VIX Error: ' + str(e))

    try:
        r = self.http.request('GET', 'https://www.google.com/finance/getprices?q=VIX&i=60&p=1d&f=c')   #f=d,o,h,l,c,v'
        s = (r.data).decode('utf-8')
        l = list(s.splitlines())
        self.VIX = Decimal(l[-1])

    except Exception as e:

        self.Debug('VIX Error: ' + str(e))  #change after last deployment

        if (type(self.VIX) is Decimal) == False:
            self.VIX = 0

LiveTradingRealTimeHandler.Run(): 在QuantConnect.Scheduling.ScheduledEvent中有一个错误,错误是UnicodeDecodeError: 'utf-8'编解码器无法解码字节0xa0,在位置57360:无效的起始字节。在main.py:line 417的OnData中的GetVix位置57405处,运行时错误:UnicodeDecodeError:'utf-8'编解码器无法解码字节0xa0,在位置57405处的无效起始字节,UnicodeDecodeError:'utf-8'编解码器无法解码字节0xa0,在位置57405处的无效起始字节Stack Trace:System.Exception:UnicodeDecodeError:'utf-8'编解码器无法解码字节0xa0,在位置57405处:无效的起始字节在main.py:line 417的OnData中的GetVix位置458---> Python.Runtime.PythonException:UnicodeDecodeError:'utf-8'编解码器无法解码字节0xa0,在位置57405处:无效的起始字节在Python.Runtime.PyObject.Invoke(Python.Runtime.PyTuple args,Python.Runtime.PyDict kw) [0x00033] in <7ada479175184ff388929ece541bbdb4>:0 at Python.Runtime.PyObject.InvokeMethod(System.String name,Python.Runtime.PyTuple args,Python.Runtime.PyDict kw) [0x00007] in <7ada479175184ff388929ece541bbdb4>:0 在<7ada479175184ff388929ece541bbdb4>:0的Python.Runtime.PyObject.TryInvokeMember(System.Dynamic.InvokeMemberBinder binder,System.Object[] args,System.Object& result) [0x0003e] at (wrapper dynamic-method) System.Object:CallSite.Target(System.Runtime.CompilerServices.Closure,System.Runtime.CompilerServices.CallSite,object,QuantConnect.Data.Slice) 在QuantConnect.AlgorithmFactory.Python.Wrappers.AlgorithmPythonWrapper.OnData(QuantConnect.Data.Slice slice) [0x00088] in <4d2bac9c1f474180a99afaeed3fe5b8a>:0 at QuantConnect.Lean.Engine.AlgorithmManager.Run(QuantConnect.Packets.AlgorithmNodePacket job,QuantConnect.Interfaces.IAlgorithm algorithm,QuantConnect.Lean.Engine.DataFeeds.IDataFeed feed,QuantConnect.Lean.Engine.TransactionHandlers.ITransactionHandler transactions,QuantConnect.Lean.Engine.Results.IResultHandler results,QuantConnect.Lean.Engine.RealTime.IRealTimeHandler realtime,QuantConnect.Lean.Engine.Server.ILeanManager leanManager,QuantConnect.Lean.Engine.Alpha.IAlphaHandler alphas,System.Threading.CancellationToken token) [0x013e5] in <7d8df6f15cb44723bde6b3f6cea9f521>:0---内部异常堆栈跟踪结束---

1
旁边的问题,为什么你说 if (type(self.VIX) is Decimal) == False: 而不是 if not isinstance(self.VIX, Decimal): - Edward Minnix
1
请发布完整的错误回溯格式,这很可能会显示错误发生的行。 - bluesmonk
@EdwardMinnix 我想最好这样写 if not isinstance(self.VIX, Decimal):。我不是专业的编程人员,所以通常只是找到一个可行的方法。 - Pier-Olivier Marquis
1个回答

1
当在Python中捕获异常时,或任何语言中都是如此,您需要非常清楚地知道要捕获哪些异常,否则您的程序仍将崩溃。您正在捕获“Exception”,但您的程序因“UnicodeDecodeError”而崩溃,因此您应该尝试捕获并适当处理该错误。
尝试使用以下代码:except UnicodeDecodeError as e:

9
捕获 except (Exception, UnicodeDecodeError) as e: 似乎没有意义?Exception 是所有异常的基类,捕获更具体的异常会更好,不是吗? - Chris_Rands
5
但是 Exception 是其他异常的基类(基于 BaseException),因此它应该可以捕获任何种类的良好实现的异常。 - bluesmonk
2
但是UnicodeDecodeErrorException的子类,因此可以捕获它。尝试运行最小示例:try: raise UnicodeDecodeError('1',b'2',3,4,'5') except Exception as e: print(e) - Edward Minnix
1
@J0hn 我试过了,它可以工作。我也像Chris_Rands一样认为基本异常应该捕获它,但显然我必须指定它。谢谢。 - Pier-Olivier Marquis
1
@Pier-OlivierMarquis 我相信其他原因解决了你的问题。 - Chris_Rands
显示剩余9条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接