Python 试图了解如何在我的代码中使用异常处理

Python 试图了解如何在我的代码中使用异常处理,python,Python,我正在阅读雅虎的股票数据,这些数据和CSV文件中提供给我的“股票代码”有关。然而,一些股票代码实际上在雅虎上是不可用的,所以我想知道是否有一种方法可以通过异常处理在我下面的代码中解释这一点 import pandas import pandas.io.data as web import datetime import csv f1=open('C:\Users\Username\Documents\Programming\Financialdata.csv') #Enter the loca

我正在阅读雅虎的股票数据,这些数据和CSV文件中提供给我的“股票代码”有关。然而,一些股票代码实际上在雅虎上是不可用的,所以我想知道是否有一种方法可以通过异常处理在我下面的代码中解释这一点

import pandas
import pandas.io.data as web
import datetime
import csv

f1=open('C:\Users\Username\Documents\Programming\Financialdata.csv') #Enter the location of the file
c1= csv.reader(f1)
tickers =[]
for row in c1:          #reading tickers from the csv file
    tickers.append(row)
    start=datetime.datetime(2012,1,1)
    end=datetime.datetime(2013,1,1)
    l=[]; m=[]; tickernew=[]
    i=0;j=0; k=0; z=[]
    for tick in tickers[0]:
        f=web.DataReader(tick,'yahoo', start,end)
        if len(f)==250:         #checking if the stock was traded for 250 days
            tickernew.append(tick)      #new ticker list to keep track of the new index number of tickers 
            k = k + 1               #k keeps track of the number of new tickers
            for i in range(0,len(f)-1):
                m.append(f['Adj Close'][i+1]/f['Adj Close'][i])    #calculating returns

当然。您的第一步应该是查看由于您提到的无效输入而导致程序崩溃时得到的回溯

然后,简单地用try/except将要崩溃的代码行包装起来。好的Python风格鼓励您明确处理的异常类型。因此,例如,如果崩溃引发“ValueException”,则您需要执行以下操作:

try:
  bad_line_of_code
except ValueException:
  handle_the_issue
阅读可能是有益的。