Python programmers to share good exception handling mechanism of entry

  Good programmers Python Share exception handling mechanism of entry , an exception is an event, that event affect the normal execution of the program will occur during program execution. python provides two very important functions to handle the python exceptions and errors occur in the operation of the program. Today's Python entry-learning courses give you explain exception handling mechanism.

 

  When an exception occurs in your program needs to exception handling. When such as when you open a file that does not exist, when your program has some invalid statements , Python will prompt you an error exists. As programmers, we want the program to be robust enough, even if an exception occurs, it can well recover. So how effectively prevent abnormal it ? You can adopt the following several ways:

 

  1 , the try / the except clause

 

  try ... except statement can be used to capture and handle errors. A general statement in try block , an error handling in the statement except block.

 

  grammar:

 

  try:

 

  Code block is detected

 

  except Exception type:

 

  try Once an abnormality is detected, the logic executed at this location

 

  In Python in, the try / the except statement handler to perform some unusual circumstances arising in the course. Note that, the try the except ... should be used sparingly because of an unusual process itself is that you attach to your program logic, and your main job is not related to this kind of thing plus more , and will result in your code less readable. Only in the case of some unforeseen anomalies, it should be added to the try ... the except , other logical errors should be corrected as much as possible.

 

  2else

 

  else code block is not necessary, it only need to rely on try the code executes successfully only when needed. It try-except the structure of the following positions:

 

  try:

 

  Fragment 1

 

  except exception object :

 

  Fragment 2

 

  else:

 

  Segment 3

 

  try-except-else works a block of code: Python try to do try block of code fragment 1 code fragment 1 code may raise an exception should be the only code that does not throw an exception code not on the try code block ( fragment 1) . If the fragment 1 code exception occurs on the implementation of fragment 2 code, exception handling, otherwise, if the fragment 1 code no exception occurs, the implementation of fragment 3 code fragment 3 code should be the only segment 1 of code of success executing code only needs to run.

 

  3 , a finally clause

 

  Occurs when you are reading or has not closed the file files how abnormal that do ? You should use try ... finally statement to release resources.

 

  try语句可以有一个可选的finally子句。无论什么情况,该子句都会被执行,通常用于释放外部资源。一旦使用,无论文件是否打开成功,都必须清理资源。所以,在finally子句中使用close(),可以确保即使发生异常,文件也能够被关闭。


Guess you like

Origin blog.51cto.com/14249543/2411166