๐ก️ Exception Handling in Python: Advanced Guide for Beginners
In programming, exceptions are errors that happen when the program is running. Exceptions are runtime errors that disrupt normal flow.
If we don’t handle these errors, our program might crash. Python gives us a way to catch and handle exceptions, which helps catch these errors so the program can continue to run gracefully or show a friendly message to the user.
๐ค Why Use Exception Handling?
Consider a program that divides two user-input numbers. If a user inputs 0
as the divisor, a division by zero error (ZeroDivisionError
) occurs. Without handling, your program crashes. With exception handling, you can:
-
Rescue the program from crashing
-
Display helpful error messages
-
Prevent invalid data from breaking your logic
๐งฉ Core Syntax
try:
# code that may raise an exception
except SpecificError as e:
# handle the error
else:
# optional: runs when no exception was raised
finally:
# optional: runs regardless, commonly used for clean-up
-
try
: Wrap potentially risky operations -
except
: Catch and handle one or more specific exceptions -
else
: Execute only if no exceptions occur -
finally
: Always execute (e.g., closing files or releasing resources)
Let’s understand this
with an example.
๐ธ Example 1:
Division Program
๐ก Output Scenarios:
1.
Normal input:
2. Division by zero:
3. Invalid Input:
๐งช Example: User Input & Division (Code block)
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter a valid integer.")
else:
print(f"Result: {result}")
finally:
print("Operation complete.")
How this works:
-
ZeroDivisionError
: Caught when divisor is zero -
ValueError
: Non-integer input -
else
: Displays result if no error -
finally
: Runs every time
๐ Common Built-in Exceptions
-
ZeroDivisionError
– division by zero -
ValueError
– conversion errors -
TypeError
– unsupported operations -
FileNotFoundError
– file operations fail
๐ง Best Practices
-
Catch only specific exceptions (e.g.,
ZeroDivisionError
, not a generalException
) -
Avoid bare
except:
, which hides unexpected errors. -
Keep
try
blocks minimal – include only code that might fail -
Use
finally
for cleanup – close files or release resources. -
Log or print exception details using
except Exception as e:
for debugging purposes
๐ง Advanced Patterns: Raising and Chaining Exceptions
You can also raise custom exceptions or re-raise caught ones:
def divide(x, y):
try:
return x / y
except ZeroDivisionError as e:
raise ValueError("Invalid division") from e
This approach wraps an internal error in a clearer, higher-level exception—while preserving original context.
๐ Summary
-
Use try to wrap code that might cause an error.
-
Use Except to Handle specific exceptions to maintain clarity
-
Use
else
for code that runs only if there's no error and success paths. Use
finally
for code that should run no matter what (like essential cleanup).-
Apply best practices to write robust, maintainable code.
Exception handling makes your program more reliable and user-friendly.
Mastering exception handling transforms your scripts from fragile to resilient—making them suitable for real-world applications!
No comments:
Post a Comment