Sitemap
CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Python Basics: Exception Handling

2 min readNov 6, 2025

--

Press enter or click to view image in full size

Code sometimes fails — maybe because of user input, missing files, or unexpected values. Python’s exception handling keeps your program running smoothly even when errors pop up.

1. What Are Exceptions?

An exception is an error detected during program execution.

Get Gitanjali’s stories in your inbox

Join Medium for free to get updates from this writer.

Without handling, exceptions will crash your code:

print(1 / 0)
# ZeroDivisionError: division by zero

2. The try and except Blocks

Handle errors gracefully using try and except. Place risky code in try. If an error occurs, the except block runs instead of stopping your program.

try:
num = int(input("Number: "))
print(10 / num)
except ZeroDivisionError:
print("Can't divide by zero!")
except ValueError:
print("That wasn't a valid number.")

You can catch specific errors or use a generic except for any error.

3. The finally Block

Use finally for cleanup—this code always runs, error or not.

try:
f = open("data.txt")
# some file work
except FileNotFoundError:
print("File not found!")
finally:
print("Finished trying to read file.")

4. Why Use Exception Handling?

  • Prevent your program from suddenly crashing
  • Display helpful error messages
  • Safely deal with files, user input, or external resources

Summary

  • Use try and except to handle problems as they happen
  • Always clean up with finally
  • Catch specific exceptions for smarter code

Practical exception handling makes your programs more robust and user-friendly!

--

--

Published in CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers