Familiarization with Try...Except Tool in Python

python try except tutorial
10 November 2024

One of the important and practical capabilities in Python is the use of try and except blocks, which are used for error management. In real projects, this tool helps us ensure that our program runs smoothly and predictably, even if a user inputs incorrect data or if the information we are looking for is not available.

Suppose you are writing a program to receive numeric input from the user. You may encounter an error that causes the program to stop if the user mistakenly inputs a string instead of a number. Here, the try...except structure allows us to identify the error and easily manage it so that the program can continue to run.

Not only does try...except assist us in managing errors, but there are also other constructs such as else and finally that can be used for managing different parts of the program execution based on the occurrence or non-occurrence of errors.

For example, we can write code that, in the case of an error, prints the error message, and in the case of no errors, executes a different part of the code to ensure a user experience without issues.

Tools for managing errors in Python not only makes your code more robust and reliable, but also provides better insight into the types and potential errors that might occur in order to manage them better in the future.

try:
number = int(input("Enter a number: "))
print(f"You entered: {number}")
except ValueError:
print("That was not a valid number!")

Explanation of Error Line by Line:

try:
In this line, we start a try block that tells Python there is potential code here that might cause an error.

number = int(input("Enter a number: "))
This line takes an input from the user and attempts to convert it into an integer.

print(f"You entered: {number}")
If the conversion is successful, the entered number will be printed.

except ValueError:
This block will run if we encounter a ValueError, meaning the user entered something that is not a valid number.

print("That was not a valid number!")
In this line, a message is printed for the user to inform them that the input was invalid.

FAQ

?

Why should we use try...except?

?

Can I only catch one type of error?

?

Can I use both else and finally at the same time?