Actually, I write bugs for a living. The more bugs you write, the more people you hire, and the industry will thrive. Ah ~ the winter of the Internet industry is because of you people, all like to capture anomalies, although just a joke, but reflects the importance of anomalies.

What can I do after this course?

After learning this course, we can have a general understanding of the capture and processing of exceptions. Then our program will not report errors!

How long does the course take?

10-15 minutes

Course content

What is an exception?

In a word: the program does not perform as we expect, and an error is an exception.

Why handle exceptions?

If the exception is not handled, it may cause the program to break or crash, terminating the execution.

Classic primer

In the demo above we saw Python’s syntax for catching exceptions. The try keyword is followed by business logic, and the except keyword is followed by the exception to be caught. The denominator is 0. If no exception is caught, the program will report an error. The Demo is going to print out that 0 can’t be the denominator.

Catch file errors for common exceptions

This Demo is also more commonly used, often used in reading and writing files, has not learned file operation, understand it can be.

Common exception catch type error

Catch multiple exceptions

You can also write:

Or you can simply catch all exceptions:

Finally and else comparison

If a block of code is executed when there are no exceptions, use else

If you want to execute a block of code with or without exceptions, use finally

summary

This lesson focuses on exception catching and handling, as well as common exceptions.

What’s next?

I’m excited to see that we’ve learned most of the basic support. Next we’ll learn about the Python standard library

Follow the public account, reply Python basics download all the code +PDF ebook