Introduction based on Python exceptions and method analysis of exception handling

Exception handling is a topic of concern in any programming language. Good exception handling can make your program more robust, and clear error messages can help you fix problems quickly. In Python, the try/except/finally block is used to handle exceptions, unlike high-level languages. If you have experience with other programming languages, it is not difficult to practice.

What is an exception?

Error

In terms of software, errors are grammatical or logical. Errors are grammatical or logical.

A syntax error indicates that the software is structurally flawed, so that it cannot be interpreted by the interpreter or the compiler cannot compile. These errors must be corrected before the program is executed.

When the grammar of the program is correct, the rest is a logic error. Logical errors may be due to incomplete or illegal input;

In other cases, it may be that the process that the logic cannot generate, calculate, or output results cannot be executed. These errors are often referred to as domain errors and range errors, respectively.

When python detects an error, the python interpreter indicates that the current stream is no longer executable. An exception occurred at this time.

2. Abnormal

The best description of an exception is: it is the behavior taken outside the normal control flow because of a program error.

This behavior is divided into two phases: the first is the error that caused the exception, and then the phase of detection (and taking possible measures).

The first phase occurs after an abnormal condition (sometimes called an exception condition) occurs.

As long as an error is detected and an exception condition is recognized, an exception occurs in the interpreter. Priming can also be called triggering, throwing or generating. The interpreter informs the current control flow that an error has occurred.

Python also allows programmers to throw exceptions themselves. Whether it is caused by a Python interpreter or a programmer, an exception is a signal that an error has occurred.

The current stream will be interrupted to handle this error and take the appropriate action. This is the second stage.

The exception handling occurs in the second phase, and after the exception is raised, many different operations can be invoked.

You can ignore the error (record the error but take no action, terminate the procedure after taking remedial action) or try to continue the program after mitigating the impact of the problem.

All of these operations represent a continuation, or branch of control. The key is that the programmer can indicate how the program will execute when the error occurs.

Python uses an exception object to represent an exception. When an error is encountered, an exception is thrown.

If the exception object is not being processed or caught, the program terminates execution with a so-called traceback.

Exception handling

To catch exceptions, use the try/except statement.

The try/except statement is used to detect errors in the try block, allowing the except statement to catch exception information and process it.

If you don't want to end your program when an exception occurs, just grab it in the try.

grammar:

The following is the syntax of a simple try....except...else:

The working principle of Try is that when starting a try statement, python marks the context of the current program, so that when the exception occurs, it can be returned here, the try clause is executed first, and what happens next depends on the execution time. Whether an exception has occurred.

If an exception occurs when the statement after the try is executed, python jumps back to try and executes the first exception clause that matches the exception. After the exception is processed, the control flow passes through the entire try statement (unless it raises a new one when processing the exception). Anomaly).

If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (this will end the program and print the default error message).

If no exception occurs during the execution of the try clause, python will execute the statement after the else statement (if there is an else), and then control the flow through the entire try statement.

Use except without any exception type

You can use except without any exception type, as in the following example:

The above-style try-except statement captures all exceptions that occur. But this is not a good way, we can not identify specific exception information through the program. Because it captures all the exceptions.

Use exception with multiple exception types

You can also use the same except statement to handle multiple exceptions, as follows:

Try-finally statement

The try-finally statement will execute the final code regardless of whether an exception occurs.

When an exception is thrown in the try block, the finally block code is executed immediately.

After all statements in the finally block are executed, the exception is fired again and the except block code is executed.

The content of the parameter is different from the exception.

Let's look at an example:

Introduction based on Python exceptions and method analysis of exception handling

Click for larger image

Summarized as follows:

The except statement is not required, the finally statement is not required, but there must be one, otherwise there is no meaning of try.

There can be more than one exception statements. Python will match the exception you specify in the order of the except statement. If the exception has already been processed, it will not enter the following except statement.

The except statement can specify multiple exceptions in the form of tuples, see the example code.

If the exception type is not specified after the except statement, all exceptions are captured by default. You can get the current exception through logging or sys module.

If you want to repeat the throw after capturing the exception, use raise, without any parameters or information.

It is not recommended to capture and throw the same exception, please consider refactoring your code.

It is not recommended to capture all exceptions without clear logic, and it is possible that you have hidden very serious problems.

Try to use the built-in exception handling statement to replace the try/except statement, such as the with statement, getattr() method.

Experience case

Passing the exception re-raise Exception caught the exception, but wants to re-throw it (passing the exception), using the raise statement with no arguments:

In Python 2, in order to maintain the complete information of the exception, you must not add an exception object after the raise after you capture it again, otherwise your trace information will be truncated from here. The above is the easiest way to rethrow an exception.

There are also some tricks to consider, such as updating the information about the exception before throwing the exception.

If you are interested in learning more, it is recommended to read this blog.

Http://

Python 3 has improved on duplicate delivery exceptions, so you can try it yourself, but the recommendation is the same as above.

Exception and BaseException

Should we use Exception or BaseException when we want to catch a generic exception? I suggest that you still look at the official documentation, what is the difference between these two exceptions? Look at the inheritance relationship between them.

From the perspective of the Exception hierarchy, BaseException is the most basic exception class, and Exception inherits it. In addition to all the Exceptions, BaseException contains three exceptions: SystemExit, KeyboardInterrupt and GeneratorExit.

It seems that your program should use Exception instead of BaseException when catching all exceptions, because the other three exceptions belong to higher-level exceptions, and it should be reasonable to hand them to Python's interpreter.

Except Exception as e and except Exception, e

The code example is as follows:

In the Python 2 era, you can use either of the above two methods. In Python 3 you can only use the first one, and the second one is discarded. The first kind of writing is more readable, and for the compatibility of the program and the cost of later porting, please also abandon the second method.

Raise "Exception string"

It seems like a very succinct way to throw a string as an exception, but it's actually a very bad habit.

If the above statement throws an exception, then it would be like this:

Introduction based on Python exceptions and method analysis of exception handling

This was acceptable before Python 2.4, but not specifying an exception type might prevent the downstream from properly catching and handling the exception, causing your program to hang. To put it simply, this kind of writing is a bad habit of the feudal era and should be thrown away.

Use the built-in grammar paradigm instead of try/except

Python itself provides a number of grammar paradigms that simplify the handling of exceptions, such as the StopIteration exception handled by the for statement, allowing you to write a loop smoothly.

The with statement automatically calls the close file operation in finally after opening the file. When writing Python code, we should try to avoid using try/except/finally thinking when dealing with this situation.

For another example, when we need to access an indeterminate property, chances are you would write code like this:

In fact, you can use the simpler getattr() to achieve your goal.

Best Practices

Best practices are not limited to programming languages, just some of the rules and pitfalls.

1. Only handle exceptions you know, avoid catching all exceptions and swallow them.

2. The exception thrown should explain the reason, sometimes you know the type of exception can not guess why.

3. Avoid doing something meaningless in the catch block.

4. Don't use exceptions to control the process, so your program will be incomprehensible and difficult to maintain.

5. If necessary, remember to use finally to free up resources.

6 If necessary, don't forget to do the cleanup or rollback after handling the exception.

Abnormal quick check list

Introduction based on Python exceptions and method analysis of exception handling

Faceplate

YLTelecom produces a variety of network faceplate, these faceplates are compatible with our keystone jacks. We have 86 type faceplate, 120 type faceplate, USA Type faceplate,UKtype faceplate, Australian Type Faceplate, French Type Faceplate, and also German Type Faceplate. These faceplate are available with 1 port, 2 port, 3 port, 4 port, 5 port, and 6 port. They are complaint with international standards and with good material. Due to high quality, our faceplate has recognized by international customers for many years.

We are Quality UTP / FTP Network Keystone Jack Plastic Faceplates with Shutter RJ45 Module manufacturers & exporter,we pffer you many type of Faceplate,like Rj45 Faceplate,Telephone Faceplates,86type Face plate.We can promise you the good quality and low price.

Network Faceplate, USB Faceplate, Rj45 Faceplate, Telephone Faceplates

NINGBO YULIANG TELECOM MUNICATIONS EQUIPMENT CO.,LTD. , https://www.yltelecom.com