error and exception handling¶
- In Python, errors and exceptions are mechanisms to handle unexpected situations that arise during program execution.
- They help prevent your program from crashing abruptly and offer ways to recover gracefully or provide meaningful feedback to the user.
- Types of Errors
- Syntax Errors: These are violations of Python's grammar rules, like typos or missing colons. These are detected before the program even runs.
- Exceptions: These are runtime errors that occur during program execution. They can be caused by various factors like division by zero, accessing non-existent elements, or file-related issues.
- Exception Handling with
try-except
- The primary mechanism for handling exceptions in Python is the
try-except
block
- The primary mechanism for handling exceptions in Python is the
In [ ]:
Copied!
try:
# Code that might raise an exception
result = 10 / 0 # This will cause a ZeroDivisionError exception
print(result)
except ZeroDivisionError:
print("Oops! You cannot divide by zero.")
try:
# Code that might raise an exception
result = 10 / 0 # This will cause a ZeroDivisionError exception
print(result)
except ZeroDivisionError:
print("Oops! You cannot divide by zero.")
Explanation
try:
: This block contains the code that might raise an exception.except ZeroDivisionError:
: Thisexcept
block handles theZeroDivisionError
exception specifically. If any code within thetry
block raises this exception, the code within thisexcept
block will execute instead.- You can have multiple
except
blocks to handle different types of exceptions.
else
Clause- The
else
clause (optional) is used when no exception occurs within thetry
block. The code within theelse
block executes only if thetry
block completes successfully without raising an exception.
- The
In [ ]:
Copied!
try:
result = 10 / 5
print(result)
except ZeroDivisionError:
print("Oops! You cannot divide by zero.")
else:
print("The division operation was successful.")
try:
result = 10 / 5
print(result)
except ZeroDivisionError:
print("Oops! You cannot divide by zero.")
else:
print("The division operation was successful.")
finally
Clause- The
finally
clause (optional) executes regardless of whether an exception occurs or not. It's commonly used to release resources or perform cleanup tasks.
- The
In [ ]:
Copied!
try:
file = open("myfile.txt", "r") # Open a file
data = file.read()
finally:
if file:
file.close() # Close the file even if an exception occurs
try:
file = open("myfile.txt", "r") # Open a file
data = file.read()
finally:
if file:
file.close() # Close the file even if an exception occurs
- Common Exceptions
ZeroDivisionError
: Attempting to divide by zero.IndexError
: Trying to access an element at an invalid index (out of bounds).NameError
: Referencing a variable that hasn't been defined.KeyError
: Trying to access a key that doesn't exist in a dictionary.FileNotFoundError
: Attempting to open a file that doesn't exist.
- Raising Exceptions
- You can intentionally raise exceptions using the
raise
statement. This is useful for signaling errors from within your code.
- You can intentionally raise exceptions using the
In [ ]:
Copied!
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
validate_age(-5) # This will raise a ValueError
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
validate_age(-5) # This will raise a ValueError
- Key Points
- Use exception handling (
try-except
) to handle unexpected errors gracefully and prevent program crashes. - Employ specific
except
blocks to handle different exception types. - The
else
clause executes only if no exception occurs in thetry
block. - The
finally
clause is always executed, regardless of exceptions. - Understand common exceptions to anticipate potential errors in your code.
- Use exception handling (