Error and exception handling in Python

Tram Ho

Today, I continue to learn about you “Errors and exceptions”, the next blog post is in the series “Explore Python Citadel” , part of Python Tutorial.

In this article, I will explore the types of errors and exceptions in Python as well as how to handle and create my own exceptions.

(The contents in this series are mainly from and then rewritten or translated according to my language)

If you read from the beginning of the series here, you must have seen some code that I deliberately gave it error, in the article “I / O in Python” :

The picture above shows that there are two distinguishable types of errors: “syntax error” and “exception” .

Syntax error

Syntax error is the error that occurs when parsing, the type of error that I most often encounter.

The parser will repeat the faulty line and display a small arrow that poses as the earliest point in the line where the error was detected.

The above example shows an error detected where the print function is called, the reason is missing the “:”

Sometimes there is a syntax error but no detected position, for example at the beginning of the article “SyntaxError: positional argument follows keyword argument” indicates that the variable must be positioned before the variable by keyword.


Even if the syntax is correct, the code can still cause errors during execution. Errors found during code execution are called exceptions.

As you can see above the exceptions have many different types and will be printed with the error information.

In the above example, we have exceptions like ” ZeroDivisionError “, ” NameError “, ” TypeError

Handling exceptions

When writing programs with Python, sometimes I will deliberately let the outlier happen in order to handle them. As in the example below, input entered from the user can cause a “ValueError” exception and I will handle it by sending information to the user that they entered incorrectly.

The example above used the group of ” try… except ” statements to catch and handle the exception.

The above code works as follows:

First, the code in the “try” clause is executed

– If no exception occurs, the “except” clause will be skipped and the program ends (as when I entered 9).

If an exception occurs during code execution in the try clause, the code below it will be ignored. If the exception error coincides with the error we caught (after the keyword “except”, here is the ValueError), the except code will be executed (print “Oops! …”). And the code in try will continue to be executed.

– If an exception occurs but does not match the exception you caught, the program will stop and print the exception to the screen (the exception has not been handled).

Since many exceptions can occur:

– A “try” can go with many “except”: or use when I want to handle each except differently.

– An except can catch many types of exceptions, for example: except (RuntimeError, TypeError): or used when we want to gather many types of except into handling once.

Which ambulance comes first?

There are two code snippets like the two below, and guess the print order when example 1 and 2 are executed

Note “RotDH_NV1” is extended from Exception class

Have you researched carefully yet, have you guessed what the print order in the two examples is?

Before searching for answers, try to give your own results first.

Here is my answer, let me try it right, hen:

The first is the order of inheritance of these guys:

Exception> RotDH_NV1> RotDH_NV2> RotDH_NV3

So when the loop executes each object:

Example 1:

– If you raise to RotDH_NV1, check:

-> coincides with except RotDH_NV3 -> False, then continue

-> coincides with except RotDH_NV2 -> False, then continue

-> coincides with except RotDH_NV1 -> True, print out “RotDH_NV1”

raise RotDH_NV2 then check:

-> coincides with except RotDH_NV3 -> False, then continue

-> coincides with except RotDH_NV2 -> True, print out “RotDH_NV2”

raise RotDH_NV3 then check:

-> coincides with except RotDH_NV3 -> True, print out “RotDH_NV3”

So the output printed in example 1 is:




** Example 2: **

– If you raise to RotDH_NV1, check:

-> coincides with except RotDH_NV1 -> True, print out “RotDH_NV1”

raise RotDH_NV2 then check:

-> coincides with except RotDH_NV1 -> True, print out “RotDH_NV1”

raise RotDH_NV3 then check:

-> coincides with except RotDH_NV1 -> True, print out “RotDH_NV1”

So the output printed in example 2 is:




From the example above, I can see that when the exception is raised, when the friend hits the other, he executes it first, it is like an emergency, the ambulance comes first then takes people to the hospital first.

Sometimes an error will occur but I have not guessed what that exception is, and I often use ” except: ” with no exception, to scavenge the rest of you.

However, remember to be careful when using this friend, because he takes the basket so it is easy to hide the program’s error and make it difficult to check the idea.

Therefore, it is best to use her for the rest of the team, print the error out and raise her up to know how to actively protect the code.

Do it: catch the guy’s face and face and raise the error again so that you don’t want to make an unexpected mistake and just ignore it.

The nuns give me more attention. Have you ever used “except Exception as e:” to catch remaining exceptions?

When I use the “except Exception as e:” thing , it is convenient that I can access the properties of the ” e ” object such as e.message or e.args .

But you note that the ** “except Exception as e:” ** it is different from the “except:” . Specifically:

– ** “except:” ** catches all exception types.

“except Exception:” or “except Exception as e:” catch all types of exceptions but EXCEPT ” BaseException “, ” SystemExist “, ” KeyboardInterupt ” and ” GeneratorExist ” (It means you can get this minus. shouting, there is no silence.)

Do it if no exception raise (Do it if no exception raise)

In addition, the group “try … except” also has an optional accompanying clause “else”, which goes after all types of “except”.

This clause usually contains code to be executed if the try clause does not have any exceptions.

Using the else clause as above is better than leaving the executable code in the try clause like this:

Outliers of tomography

When an exception occurs, he has some values ​​to express himself, like what his name is, where is the house or a family of Italians, these people are often called the English name ” exception’s argument “. .

I have mentioned this before in the “except Exception as e” section with e.message and e.args .

In addition to the default returned as above, when I raise the exception, I can also pass her the specific values ​​as follows: * “raise Exception (” value 1 “,” value 2 ″) ” *

For convenience, these passed values ​​will by default be returned in the __str__() of the exception, so when calling print (e) of e in “except Exception as e” it has the value of (“Value 1”, “value 2”). Or e.args has the same value as above.

Scold when there are exceptions

In the above content, many times we shouted when the code had problems, you already know how to shout when there are exceptions, right?

That is to use the emergency call 115 =))

Just kidding, that is, using the keyword ” raise ” with the exception or going alone is fine.


Ha ha, can you believe the exceptions blame each other?

If you want it okay. Really!

Here is an example of blame, or more fancy than chained exceptions, see this code:

Above, it is clear that the IOError exception was caught, but I intentionally changed the error to RuntimeError by using “from”, the syntax helps me string IOError errors through the RuntimeError error and print both of you to the screen as above. .

But if you just want to print the “RuntimError” error, and don’t want to show the IOError anymore, you can use “from None” to disable your from exception stringing.

Then it should work like this:

Yeah, so we can make a blatant change without having to trace the origin (unless we look at the code).

Ahem, however, this guy is quite dangerous because swapping things around makes it difficult to debug, so be more careful when using.

My exception

That’s it now (meaning from start to finish), I’m working with other people’s exceptions (Python’s default exception), now I like to make my own, I simply speak human, oh wrong, user voice, and programmer’s voice are sometimes more meaningful and friendly, hihi.

When I write my program, I can create exceptions by inheriting from the class “Exception”, both directly and indirectly.

Do not explain directly, but indirectly I inherit from some exception that inherited from “Exception”, so hoai.

Usually, people create a base exception that inherits directly, and then other types of exceptions indirectly inherit “Exception” by that base exception.

Well, about the naming method, they also name after the same last name, for example, they here can be Error: Input Error, StupidError, NevermindError, … Like that

Let’s look at the example together:

Do it for me at any cost (Do it no matter what)

In the part “Do me this if there are no exceptions”, we use “else” after the except á mask, remember, that is, we execute the code when no exception occurs.

Also here, “Do this at any cost”, I use with “finally”, that is, I execute the code in finally whether an exception occurs or not.

That is, the code at this finally must always be done, they call cool “clean-up actions”.

Please see an example:

Do you have any question why you get an exception and the print still prints?

That is the mechanism of that finally, let’s learn more about how her operation is.

If a “finally” clause appears, the code belonging to this clause will execute as the last action before the try statement ends.

Below is the mechanism of action for quite complex situations with finally:

– If an exception occurs while executing the group of statements in “try”, if the exception screams but has not been captured with “except”, the group of statements in “finally” still runs first, then the new exception be shouted after.

If an exception occurs by group of statements in except or else. Once again, the group of commands in finally is run first, then the exceptions in these generators are shouted.

– If the block in try has special instructions such as “break”, “continue” or “return” that stop execution in the middle, then the group of statements in finally is executed before this group is called.

– If the block in finally contains a “return” statement, the return value will be the value from finally, not the value returned from the code block in the try.

In practice, finally is a place that holds groups of commands that serve to release resources such as files or network connections, regardless of whether these resources are used or not.

Some interesting examples of finally here:

Hey, remember to consider finally you before proceeding.

Check back to see if you understand the example?

Pre-defined cleaning jobs

In Python, there are several types of object that have pre-defined cleaning actions to return the resource when we no longer use it without knowing whether the resource is successfully used or not (like when we do it ourselves. clean resources with finally above).

This type of object can typically be described when I am working with a file.

Usually when I open a file I will use open (“filename.txt”) . The problem here is that we opened people but don’t remember to close them to recover memory resources, and can cause memory problems for large projects or files that are too heavy.

The ” with ” command allows objects such as files to ensure that memory is freed each time the code in this group of statements is executed. Therefore, it ensures that resources are recovered promptly and accurately.

Remember this example, and always use her when opening the file as best practice.

Today I know a little bit more about bugs and exceptions.

After this section, we will read together the section “Classes in Python” together.

Thank you everyone for coming home.



Share the news now

Source : Viblo