


Khusboo Tayal
In any programming language, errors are inevitable. In Python, exception handling is used to manage errors gracefully without crashing your program. Instead of showing raw error messages, you can catch exceptions and respond accordingly.
An exception is an error that occurs during the execution of a program. Common examples include:
Python uses try and except blocks to handle exceptions.
try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
In this example, the error is caught and handled without stopping the program.
You can handle multiple exception types separately:
try:
num = int("abc")
except ValueError:
print("Invalid input: not a number.")
except ZeroDivisionError:
print("You can't divide by zero.")
You can catch any exception using a generic except:
try:
x = 5 / 0
except Exception as e:
print("An error occurred:", e)
While this is useful, it’s recommended to catch specific exceptions for better clarity.
The else block runs only if no exception occurs:
try:
x = 10 / 2
except ZeroDivisionError:
print("Division error.")
else:
print("Division successful:", x)
The finally block always executes, whether an exception occurs or not. It's commonly used for cleanup tasks like closing files.
try:
f = open("file.txt")
content = f.read()
except FileNotFoundError:
print("File not found.")
finally:
print("Executing cleanup code.")
You can raise exceptions using the raise keyword:
age = -5
if age < 0:
raise ValueError("Age cannot be negative.")
This is useful for input validation or custom error handling.
You can define your own exception types by extending the Exception class:
class CustomError(Exception):
pass
try:
raise CustomError("Something went wrong.")
except CustomError as e:
print(e)
| Exception Name | Description |
|---|---|
| ZeroDivisionError | Division by zero |
| ValueError | Wrong type of value |
| TypeError | Wrong type of object |
| IndexError | Index out of range |
| KeyError | Missing key in dictionary |
| FileNotFoundError | File doesn't exist |
| ImportError | Failed to import module |
Python’s exception handling system helps you write reliable and user-friendly programs by managing runtime errors. With try, except, else, and finally, you can catch and respond to errors, ensuring your application runs smoothly.
Q1: What’s the difference between except and finally?
except handles the error; finally runs regardless of what happens.
Q2: Can I have multiple except blocks?
Yes, you can handle different error types in separate blocks.
Q3: Should I use generic except Exception?
Only when absolutely necessary. Always prefer specific exceptions.
Subscribe to our newsletter to get the latest Python tutorials, project ideas, and updates right to your inbox.
#python #pythonexceptionhandling #tryexcept #pythonerrors #pythontutorial #learnpython #pythonbeginners #pythontrycatch #pythonfinally #pythonbestpractices