Error handling is an essential part of programming that helps to gracefully manage and recover from errors during the execution of a program. In this post, we will explore how to handle errors in Python using try, except, else, and finally blocks, as well as how to raise and create custom exceptions.
1. Understanding Exceptions
Exceptions are events that disrupt the normal flow of a program’s execution. Python provides a robust mechanism to handle these exceptions and take appropriate actions to prevent program crashes.
Common Exceptions:
- SyntaxError: Raised when there is a syntax error in the code.
- TypeError: Raised when an operation is performed on an incorrect data type.
- ValueError: Raised when a function receives an argument of the correct type but an inappropriate value.
- IndexError: Raised when trying to access an index that is out of range.
- KeyError: Raised when trying to access a key that is not in the dictionary.
2. Try and Except Blocks
The try block lets you test a block of code for errors, while the except block lets you handle the error.
Example:
python
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Output:
vbnet
Error: Division by zero is not allowed.
3. Else Block
The else block lets you execute code if no exceptions were raised in the try block.
Example:
python
try:
result = 10 / 2
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("The result is:", result)
Output:
csharp
The result is: 5.0
4. Finally Block
The finally block lets you execute code, regardless of whether an exception was raised or not. It is commonly used for cleaning up resources.
Example:
python
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close()
print("File closed.")
Output:
arduino
Error: File not found.
File closed.
5. Raising Exceptions
You can raise exceptions in your code using the raise keyword.
Example:
python
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18.")
return "Access granted."
try:
print(check_age(15))
except ValueError as e:
print(e)
Output:
Age must be at least 18.
6. Creating Custom Exceptions
You can create your own exceptions by defining a new class that inherits from the built-in Exception class.
Example:
python
class CustomError(Exception):
pass
def check_number(num):
if num > 100:
raise CustomError("Number cannot be greater than 100.")
return "Number is valid."
try:
print(check_number(150))
except CustomError as e:
print(e)
Output:
javascript
Number cannot be greater than 100.
7. Multiple Except Blocks
You can have multiple except blocks to handle different types of exceptions separately.
Example:
python
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Error: Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Output (if a non-integer is entered):
typescript
Error: Invalid input. Please enter a number.
Output (if zero is entered):
vbnet
Error: Division by zero is not allowed.

Conclusion
In this post, we covered the basics of error handling in Python, including how to use try, except, else, and finally blocks, how to raise and create custom exceptions, and how to handle multiple exceptions. Proper error handling is crucial for creating robust and user-friendly applications. In the next post, we will explore Python modules and packages, which are essential for organizing and reusing code. Stay tuned!
Check out our Trending Courses Demo Playlist
Data Analytics with Power Bi and Fabric |
Could Data Engineer |
Data Analytics With Power Bi Fabic |
AWS Data Engineering with Snowflake |
Azure Data Engineering |
Azure & Fabric for Power bi |
Full Stack Power Bi |
Kick Start Your Career With Our Data Job
Social Media channels
► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizon
► KSR Datavizon Instagram :- https://www.instagram.com/ksr_datavision
► KSR Datavizon Face book :- https://www.facebook.com/KSRConsultingServices
► KSR Datavizon Playstore :- https://play.google.com/store/apps/details?id=com.datavizon.courses&hl=en-IN
► KSR Datavizon Appstore :- https://apps.apple.com/in/app/ksr-datavizon/id1611034268
Most Commented