Python Exceptions
In contrast, an exception is one among many different errors that occur while a program is being executed. The moment an exception occurs, Python will stop executing the program immediately and raise the error message. However, exceptions can be made to be handled in such a way that programs either carry on or give feedback to users.
Key Concepts
- What Is an Exception?
An exception is an event that deviates from the normal program flow. It usually results from:
- Invalid user input
- Code that tries to divide by zero
- Files or directories missing
- Issues with internet connections or APIs
- Bugs in the code
2. Popular Exceptions in Python
Some of the most common exceptions include:
ZeroDivisionError
: This occurs when there is an attempt to divide by zero.IndexError:
This occurs when a list is accessed with an invalid index.KeyError:
Occurs when a key does not exist in a dictionary.ValueError:
When a function takes an argument of correct type but incorrect valueTypeError:
The error that occurs when some operation or function is used with an object of incorrect typeFileNotFoundError:
The error that occurs when the system is unable to find a file or a directory.
Handling Exceptions
To handle exceptions, Python provides the try-except
block.
Syntax:
try:
# Code that may raise an exception
except SomeException:
# Code to handle the exception
Example:
try:
number = int(input("Enter a number: "))
print(10 / number)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("That's not a valid number!")
Else and Finally
else
block: Executes if no exception occurs.finally
block: Executes no matter what, even if an exception occurs or not.
Example:
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully.")
finally:
file.close() # This will always execute
Raising Exceptions
You can raise exceptions explicitly using the raise
keyword.
Example:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
Custom Exceptions
You can create your own exception classes by inheriting from the Exception
class.
Example:
class NegativeNumberError(Exception):
pass
try:
number = int(input("Enter a positive number: "))
if number < 0:
raise NegativeNumberError("Negative numbers are not allowed!")
except NegativeNumberError as e:
print(e)
Best Practices in Exception Handling
- Handle specific exceptions:
Except
block should be avoided unless unavoidable. - Use
finally
for cleanup: Ensure that resources, such as files or connections, are closed. - Do not hide exceptions: Throw them meaningfully or let them propagate, if they can’t be resolved.
- Log exceptions: For debugging and monitoring purposes.