2017-05-23 8 views
0

私のpythonアプリケーションでタイプエラーをチェックしたいと思います。 ValueErrorを次のように捕捉する正しい方法はありますか?PythonでValueErrorを処理する最良の方法は何ですか?

async def find_video_by_id(request): 
    try: 
     id = int(request.query['id']) 
     ... 
    except ValueError: 
     exception_message = "Incorrect type of video id was specified." 
     logger.exception(exception_message) 
     raven_client.captureException(exception_message) 
     raise ValueError(exception_message) 
    except Exception as ex: 
     logger.exception("find_video_by_id") 
     raven_client.captureException() 
     raise ex 
+0

申し訳ありませんが、ただ理解することが、あなたは例外であるときに、なぜあなたは例外を発生させていますか?私はそれを小さなコードで試してみましたが、私はそうしたときに問題があります。 –

答えて

0

カスタムおよび標準の例外を持つようにしたい場合は、あなたが以下のように行うことができます。

# Custom Exception 
class MyError(Exception): 
    pass 

try: 
    id = int(request.query['id']) #raise ValueError automatically if string cannot be parsed 
    if id == 'foo': # just to show how to raise a custom Exception 
     raise MyError 
    else: 
     bar() 
except ValueError: 
    exception_message = "Incorrect type of video id was specified." 
    logger.exception(exception_message) 
    raven_client.captureException(exception_message) 
except MyError: 
    exception_message = "Incorrect stuff." 
    logger.exception(exception_message) 
    raven_client.captureException(exception_message) 
関連する問題