Python Lesson 13: Error Handling

PYTHON

AllComputerss

4/18/20261 min read

python tutorials
python tutorials

Errors are inevitable when writing code, but Python provides powerful tools to handle them gracefully. Instead of letting your program crash, you can anticipate and manage errors using exceptions.

What Are Exceptions?

Exceptions are events that occur during program execution that disrupt the normal flow of instructions. Common examples include:

  • ZeroDivisionError → Dividing by zero

  • ValueError → Invalid value provided

  • FileNotFoundError → Trying to open a file that doesn’t exist

The Try/Except Block

The try/except block allows you to test code for errors and handle them if they occur.

Example:

try:

number = int(input("Enter a number: "))

result = 10 / number

print("Result:", result)

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

except ValueError:

print("Error: Invalid input. Please enter a number.")

How It Works:
  • Code inside the try block is executed.

  • If an error occurs, Python jumps to the matching except block.

  • The program continues running instead of crashing.

The Finally Block

The finally block runs no matter what — whether an error occurs or not. It’s often used for cleanup tasks.

try:

file = open("data.txt", "r")

content = file.read()

except FileNotFoundError:

print("File not found.")

finally:

print("Execution finished.")

Raising Exceptions

You can raise exceptions manually using the raise keyword.

x = -5

if x < 0:

raise ValueError("x cannot be negative")

Conclusion

Error handling is essential for writing robust Python programs. By using try, except, finally, and raise, you can anticipate problems, provide meaningful feedback to users, and keep your applications running smoothly. Mastering error handling will prepare you for building reliable, production-ready software.

© 2026 AllComputerss. All rights reserved.