Python

Python Advanced Errors

Python Advanced Errors

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

For Python intermediate errors here.

It continues the previous intermediate tutorial in more details. Advanced errors page contains:

  • “with” statement
  • raising an exception

With statement

The statement “with” uses exception handling.

It provides a more efficient code and is often associated with file management.

The main keyword is “with“.

The following is an example of the “with” statement.

with open("file.txt", "w") as f:
    f.write("Rewriting text")

It is quite clear from the previous examples of file handling that this method is more efficient.

The code is much cleaner when compared to try/except. In addition, there is no need of closing the file, as the “with” statement handles it.

Raising exceptions

In certain circumstances, developers need to raise exceptions.

This can happen with the keyword “raise”, alongside the help of conditional statements.

Below is an example of raising an exception, with the help of “input” and “if” statements.

guess = int(input("Please select a number between 0 and 10: "))

print(guess)
if guess < 0 or guess > 10:
    raise Exception("Only integers allowed")

# Output: Exception: Only integers allowed

The program requires an input of a number (between 0 and 10) from the user. In the case of a lower than 0 or higher than 10 input, the program raises the exception error after execution.

In addition, Python allows raising a specific error type.

The following is an example.

word = input("Choose a short word: ")

print(f"The word is {word}.")
if len(word) > 10:
    raise ValueError("Word is too long.")

The program requires a user input of a short word (less than 10 characters).

For instance, if the user word input is “chess”, the program executes and produces the output without errors.

# Output:
The word is chess.

Let’s try with a long word, for example “probabilistically”.

# Output:
ValueError: Word is too long.

Next: Python Advanced 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.