Manually raising (throwing) an exception in Python

前端 未结 8 1126
长发绾君心
长发绾君心 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:10

    Read the existing answers first, this is just an addendum.

    Notice that you can raise exceptions with or without arguments.

    Example:

    raise SystemExit
    

    exits the program but you might want to know what happened.So you can use this.

    raise SystemExit("program exited")
    

    this will print "program exited" to stderr before closing the program.

提交回复
热议问题