python中的异常

时间:2013-01-31 12:06:01

标签: python exception exception-handling error-handling

我对python很新,所以我有一个非常简单的怀疑。这是我的代码:

a=sri

try:
    print a
except Exception:
    print 'you have not put quotes for string'
else:
    print 'dont know what error it is'

如何为此编写手动异常/错误处理?

1 个答案:

答案 0 :(得分:1)

您需要处理错误的代码应该写在try子句中。您可以在except子句中编写如何处理可能的异常。

try:
    a=sri
    print a
except Exception:
    print 'you have not put quotes for string'

来自python docstry声明的更多内容。

  

try语句的工作原理如下。

     
      
  • 首先,try子句(try和except之间的语句)   关键字)被执行。
  •   
  • 如果没有异常发生,则except子句为   跳过并完成try语句的执行。
  •   
  • 如果是   执行try子句期间发生异常,其余部分   子句被跳过。如果它的类型匹配命名的异常   except关键字,执行except子句,然后执行   在try语句之后继续。
  •   
  • 如果发生异常,则会发生异常   不匹配except子句中指定的异常,它被传递给   外部审判陈述;如果没有找到处理程序,则表示未处理   异常和执行因上面显示的消息而停止。
  •