Manually raising (throwing) an exception in Python

前端 未结 8 1137
长发绾君心
长发绾君心 2020-11-22 03:38

How can I raise an exception in Python so that it can later be caught via an except block?

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 04:09

    Just to note: there are times when you DO want to handle generic exceptions. If you're processing a bunch of files and logging your errors, you might want to catch any error that occurs for a file, log it, and continue processing the rest of the files. In that case, a

    try:
        foo() 
    except Exception as e:
        print(str(e)) # Print out handled error
    

    block is a good way to do it. You'll still want to raise specific exceptions so you know what they mean, though.

提交回复
热议问题