Handling exceptions in Python is using the Try-except code block, where the Try-except code block is placed in the action that Python performs, and tells the Python program what to do if an exception occurs. Try-except This function in fact, many of the introductory books are placed in the high-level space, in the introduction of the general will not talk about this use, especially as OPS, if you often write the shell, go to Python after the estimate also rarely use this feature, This feature, I think, illustrates an important difference between the shell and Python, because Python is a real programming language, like any other programming language, Php,java, and so on, will provide the exception capture function, the code written by these programs is robust, if you read some other people write program code, In particular, some socket programming aspects of code, many are try...except ..., some also except good many, to judge a variety of situations, since this function so useful, we will come to see how to use the bar as soon as possible.
First we look at its syntax, the syntax is simple, is to put in the try-except you want to execute the code block, for example:,
Try: somecode1except Exception type/name: somecode2
This is the simplest case where multiple except sentences can be used if the situation is complex, for example:
Try: somecode0except Exception type/name 1: somecode1except exception 2: somecode2except exception 3: somecode3
Try-except also have more advanced usage, join else,finally and so on, today we do not start to say that interested can be in-depth study.
Next we look at a simple example, read and write files we often operate, a common problem is not to find the file, or file name, the path is not correct, in this case, you can use the TRY-EXCEPT code block intuitive way to deal with:
Try: withopen (filename, ' r+ ') as fp: data = Fp.read () exceptioerror: msg = ' Sorry, can not read or write this ' + filename printmsg
Let's look at a more except example, subtracting 2 numbers:
loop = 1while Loop = = 1: try: a = input (' Please enter first number > ') b = input (' Please enter second number > ') exceptnameerror: Print "Please enter a number, you cannot enter the letter" continue Exceptsyntaxerror: print "Please enter only one number." Continue print a-B try: loop = Input (' Press 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 the script, the following can be used more try-except code block, which will make your code look more professional.