Details of the exception capture method in python

  • 2020-05-26 09:33:16
  • OfStack

In use of exception handling in Python try - except code block, try - except code blocks into the python perform operation, at the same time tell python program what to do if abnormal, try - except the function introduction to many of the books are on the top space, at the time of entry 1 don't speak like this, especially as the operations staff, if you often write shell, go to the minimal estimated python using this feature, This function I think shows shell and python one important distinction, because python is a real programming language, like other programming languages php, java will provide exception handling functions, such as write the code in these programs is to robustness, if you read 1 some others write program code, especially 1 socket programming code, many are try... except... , some also have several except, to judge a variety of situations, since this function is so useful, let's take a look at how to use it as soon as possible.

First, let's take a look at its syntax. The syntax is very simple, which is to put the block of code you want to execute in try-except, such as:,


try:
  somecode1
except  Exception types / The name of the :
  somecode2

This is the simplest case. If the situation is complicated, you can use multiple except sentences, for example:


try:
  somecode0
except  Exception types / The name of the 1:
  somecode1
except  abnormal 2:
  somecode2
except  abnormal 3:
  somecode3

There are more advanced USES of try-except, including else,finally, etc., which we will not discuss today. Those who are interested in try-except can further study by themselves.

Next, let's look at a simple example. We often do the operation of reading and writing files. A common problem is that the file cannot be found, or the file name and path are not correct.


try:
  withopen(filename, 'r+') as fp:
    data = fp.read()
exceptIOError:
  msg = 'sorry, can not read or write this ' + filename
  printmsg

Let's look at one more example of except, subtracting two Numbers:


loop = 1
while loop == 1:
  try:
    a = input(' Please enter the first 1 A digital > ')
    b = input(' Please enter the first 2 A digital  > ')
  exceptNameError:
    print " Please enter a number, not a letter "
 continue
  exceptSyntaxError:
    print " Please enter only 1 A digital ."
 continue
  print a - b
  try:
    loop = input(' According to the 1 To start  > ')
  except (NameError,SyntaxError):
    loop = 0

The above two examples are the simplest use of try-except. If you want to ensure the robustness of your script, you can use the try-except code block later, which will make your code look more professional.


Related articles: