Python

Python Intermediate Errors

Python Intermediate Errors

This page covers the intermediate Python errors and continues the previous Python errors tutorial.

For Python basic errors here.

It continues the previous basic tutorial in more details. Intermediate errors tutorial contains:

  • “else” statement
  • “finally” statement

Else statement

As previously defined, “except” statements execute when there are errors in the code. Without specifying a particular error (e.g. NameError), the program produces an output with any error. Therefore, the “except” statement operates only when there are problems.

try:
  print(b)
except:
  print("Error! Something went wrong")

# Output: "Error! Something went wrong"

The “else” statement works the opposite.

Meaning, it executes only when there are no errors in the code.

Below are two scenarios, one with an error and one without.

try:
  print(b)
except:
  print("Error! Something went wrong")
else:
    print("Nothing is wrong")

# Output: "Error! Something went wrong"
b = 1

try:
  print(b)
except:
  print("Error! Something went wrong")
else:
    print("Nothing is wrong")

# Output: 1
# Output: Nothing is wrong

In the first example, the variable “b” does not exist, hence the execution error. The second, defines the variable and then tries to perform the “print()” operation, so it succeeds and prints the “else” statement.

Finally statement

The “finally” statement operates in between the “except” and “else” statements. Meaning, it always executes, whether the code produces an error or not.

The following are both examples, with errors in the code and without.

try:
  print(b)
except:
  print("Error! Something went wrong")
else:
    print("Nothing is wrong")
finally:
    print("Errors or not, I'm here")

# Output: Error! Something went wrong
# Output: Errors or not, I'm here
b = 1

try:
  print(b)
except:
  print("Error! Something went wrong")
else:
    print("Nothing is wrong")
finally:
    print("Errors or not, I'm here")

# Output: 1
# Output: Nothing is wrong
# Output: Errors or not, I'm here

Next: Python Intermediate Fundamentals Summary

by AICorr Team

We are proud to offer our extensive knowledge to you, for free. The AICorr Team puts a lot of effort in researching, testing, and writing the content within the platform (aicorr.com). We hope that you learn and progress forward.