🐍 Python Tutorial: Error Handling

In Python, errors (also known as exceptions) can interrupt the normal flow of a program. Proper error handling allows your program to respond to unexpected events gracefully rather than crashing.


1. What Are Exceptions?

Exceptions are raised when Python encounters an error during execution. Common examples include:


2. Try-Except Blocks

Use try and except blocks to catch and handle exceptions.

try:
  x = 10 / 0
except ZeroDivisionError:
  print("You can't divide by zero!")

3. Handling Multiple Exceptions

You can catch different types of exceptions using multiple except blocks:

try:
  value = int("abc")
except ValueError:
  print("Invalid input")
except TypeError:
  print("Wrong type")

4. Else and Finally

else runs if no exceptions are raised, and finally always runs (useful for cleanup):

try:
  f = open("myfile.txt")
except FileNotFoundError:
  print("File not found")
else:
  print("File opened successfully")
  f.close()
finally:
  print("Done")

5. Raising Your Own Exceptions

You can raise exceptions manually using the raise keyword:

age = -1
if age < 0:
  raise ValueError("Age cannot be negative")

Additional Resources & References


← Back : File HandlingNext: Object Oriented Programming →