- Published on
Exception Handling in Python
- Authors
- Name
- Sanjeev Sharma
- @webcoderspeed1
Introduction
In Python, an exception is a runtime error that disrupts the normal flow of the program. These exceptions can be raised intentionally by the developer or can occur unexpectedly due to errors in the code. Python has a wide range of built-in exceptions, such as ZeroDivisionError
, TypeError
, and FileNotFoundError
, among others.
- Hardware/ Operating system level:
- Arithmetic exception; divide by zero (0), underflow/ overflow
- Memory access violations, stack over/ underflow
- Language level:
- Bounds violations: illegal indices
- Value Error: invalid literal, improper casts.
- Program level:
- User defined exception
Exception handling
The try-except Block
The primary mechanism for handling exceptions in Python is the try-except block. The try block contains the code that might raise an exception, and the except block contains the code to handle the exception gracefully.
while True:
nom = int(input("Enter no."))
dnom = int(input("Enter no."))
try:
print(f"div of nums=${nom//dnom}")
print("end of div block")
except:
print("Some error")
print("end of code")
except (ValueError, ZeroDivisionError) as obj:
print(obj)
# Note: Merging two exception by using tuple
else:
break
try:
fp = open("log.txt", "a")
nom = int(input("enter nom:"))
s = f"div of nums = {nom//dnom}"
fp.write(s)
except(ValueError, ZeroDivisionError) as obj:
fb.write(str(obj) + "\n")
finally:
fp.close()
print("finally code invoked")
Assert
The assert statement in Python is a debugging aid that tests a condition as an internal self-check in your code. It's used to express the assumption that a certain condition will be true during the execution of the program. If the condition is false, an AssertionError exception is raised, halting the program.
The syntax of the assert
statement is as follows:
assert expression[, message]
Here, expression is the condition that you expect to be true. If it evaluates to False, the AssertionError is raised. The optional message parameter can be included to provide additional information about the assertion.
Let's look at some examples to illustrate the use of the assert statement:
x = 10
# Using assert to check if x is positive
assert x > 0, "Value of x must be positive"
# If x is not positive, AssertionError will be raised with the specified message
print("Program continues...")
In this example, the assert statement checks if the variable x is greater than 0. If it's not, the program will terminate with an AssertionError and the specified message.
def divide(a, b):
assert b != 0, "Cannot divide by zero"
return a / b
result = divide(10, 2) # This will work fine
print("Result:", result)
result = divide(10, 0) # This will raise AssertionError
print("Result:", result) # This line won't be reached if an exception occurs
Here, the divide function uses assert to ensure that the denominator (b) is not zero before performing the division.
def calculate_percentage(score, total):
assert 0 <= score <= total, "Invalid score value"
return (score / total) * 100
percentage = calculate_percentage(75, 100) # This will work fine
print("Percentage:", percentage)
percentage = calculate_percentage(110, 100) # This will raise AssertionError
print("Percentage:", percentage) # This line won't be reached if an exception occurs
In this example, the assert statement is used to verify that the score is within the valid range (0 to total).
It's important to note that the assert statement is typically used during development and debugging. In production code, you may want to handle such conditions more gracefully using proper error-handling mechanisms like try and except.
Raising Exceptions
Developers can raise exceptions explicitly using the raise statement. This is useful when a certain condition is met, and you want to notify the program about an exceptional situation.
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(f"Error: {e}")
else:
print("Result:", result)
In this example, the divide function raises a ValueError if the denominator (b) is zero. The except block then catches and handles the exception.
Custom Exceptions
Developers can create custom exceptions by inheriting from the built-in Exception class. This is beneficial when you want to define specific types of errors for your application.
class CustomError(Exception):
pass
def my_function(value):
if value < 0:
raise CustomError("Negative values are not allowed")
try:
my_function(-5)
except CustomError as ce:
print(f"Custom Error: {ce}")
else:
print("Function executed successfully")
In this example, the my_function
raises a CustomError
if it receives a negative value. The except
block then catches and handles the custom exception.
Conclusion
Exception handling is not a mere formality in Python programming; it's a cornerstone of writing reliable and maintainable code. By embracing best practices, staying informed about common mistakes, and exploring emerging trends, developers can navigate the complex landscape of exceptions with confidence.
FAQs
- What is the significance of exception handling in Python?
Exception handling ensures that a program gracefully handles runtime errors, preventing abrupt crashes and providing a smoother user experience.
- Can I create my own custom exceptions in Python?
Yes, Python allows developers to create custom exceptions, tailoring error messages and responses for specific scenarios.
- How does logging exceptions contribute to debugging?
Logging exceptions provides a systematic record of errors, aiding developers in identifying and resolving issues during the debugging process.
- What are the common mistakes to avoid in exception handling?
Common mistakes include neglecting potential exceptions, providing vague error messages, and failing to log exceptions, which can compromise code reliability.
- Where can I find community resources for learning more about exception handling?
Online tutorials, documentation, and community forums are excellent resources for developers looking to enhance their knowledge of exception handling in Python.