Error Handling in Python: Building Robust Apps with Try-Except Blocks
Welcome to Cyber Supto! I'm Supto.
When building Python applications, errors and exceptions are inevitable. Programs can fail due to invalid input, missing files, network problems, or unexpected conditions. Handling these errors properly ensures your application is robust, user-friendly, and professional.
In Python, error handling is done using try-except blocks, along with finally and else clauses. Understanding these concepts is essential for building applications that don’t crash unexpectedly and can gracefully recover from problems.
Table of Contents
- What Are Exceptions?
- Common Python Exceptions
- Basic Try-Except
- Handling Specific Exceptions
- Using Else and Finally
- Raising Exceptions Manually
- Custom Exception Classes
- Best Practices for Error Handling
- Frequently Asked Questions
What Are Exceptions?
An exception is an event that occurs during program execution that disrupts normal flow. When Python encounters an error, it raises an exception. If not handled, the program crashes and prints a traceback.
Example of an unhandled exception:
num = int("abc") # ValueError
Output:
ValueError: invalid literal for int() with base 10: 'abc'
Common Python Exceptions
| Exception | When It Occurs |
|---|---|
| ValueError | Invalid value for a function or operation |
| TypeError | Operation applied to wrong type |
| IndexError | Accessing invalid list or tuple index |
| KeyError | Accessing missing dictionary key |
| FileNotFoundError | File operation on a missing file |
| ZeroDivisionError | Division by zero |
| AttributeError | Accessing undefined object attribute |
Basic Try-Except
The simplest way to handle errors is using try-except:
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a number.")
Explanation:
- try: code that might cause an exception
- except: code executed if an exception occurs
Handling Specific Exceptions
You can catch multiple specific exceptions:
try:
data = [1, 2, 3]
print(data[5])
except IndexError:
print("Index out of range!")
except ValueError:
print("Invalid value!")
This ensures you handle only the exceptions you expect, keeping the code predictable.
Using Else and Finally
Python allows else and finally clauses with try-except:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input!")
else:
print("You entered:", num)
finally:
print("Execution finished.")
- else: runs if no exception occurs
- finally: runs always, even if exception occurs
Example Output (valid input):
Enter a number: 10 You entered: 10 Execution finished.
Example Output (invalid input):
Enter a number: abc Invalid input! Execution finished.
Raising Exceptions Manually
You can create exceptions manually using raise:
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
print("Age is:", age)
check_age(-5)
Output:
ValueError: Age cannot be negative
This allows validation and enforces rules in your application.
Custom Exception Classes
For complex applications, you can define your own exceptions:
class InsufficientBalanceError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError("Not enough funds!")
return balance - amount
try:
new_balance = withdraw(1000, 1500)
except InsufficientBalanceError as e:
print(e)
Output:
Not enough funds!
Best Practices for Error Handling
- Catch specific exceptions, not a generic except:
- Use finally for cleanup actions like closing files
- Raise exceptions for invalid states instead of returning special values
- Log errors for debugging
- Avoid using exceptions for normal flow control
- Keep try blocks small, don’t wrap unnecessary code
Real-World Example: Reading a File Safely
try:
with open("data.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
except IOError:
print("Error reading file")
else:
print(content)
finally:
print("File operation completed.")
Frequently Asked Questions
| Question | Answer |
|---|---|
| What is the difference between an exception and an error? | Exceptions are events detected during execution that can be handled. Errors like syntax errors cannot be handled at runtime. |
| Can I catch multiple exceptions in one except block? | Yes, you can use parentheses: except (ValueError, TypeError): |
| Is finally always executed? | Yes, even if an exception is raised or caught. |
| Should I use exceptions for normal logic? | No, exceptions are for unexpected situations, not regular program flow. |
| Can I create custom exceptions? | Yes, by subclassing the Exception class. |
Conclusion
Error handling is a critical skill for any Python developer. Using try-except blocks, along with else and finally, you can build programs that handle unexpected situations gracefully. Advanced error handling with custom exceptions ensures your apps are robust, maintainable, and professional.
By mastering error handling, your Python applications will be safer, user-friendly, and ready for real-world challenges.
Thanks for reading on Cyber Supto! I'm Supto. Keep learning, coding, and building Python applications the professional way!
Post a Comment