Errors and exceptions are a part of any programming language. They occur when something goes wrong during the execution of a program. Understanding how to handle these errors and exceptions is crucial for creating robust and reliable programs. This guide will cover the basics of error handling and exceptions in Python, with detailed explanations and examples.
Syntax Errors: These are errors in the syntax of the code. They are detected by the Python interpreter when the code is parsed and must be corrected before the code can run.
You can catch specific exceptions to handle different types of errors differently.
Example:
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("You can't divide by zero!")
The else block lets you execute code if no exceptions were raised.
Example:
try:
value = int(input("Enter a number: "))
result = 10 / value
except (ValueError, ZeroDivisionError) as e:
print(f"An error occurred: {e}")
else:
print(f"Result: {result}")
The finally block lets you execute code, regardless of whether an exception was raised or not. It’s typically used to release resources, such as closing a file.
Example:
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
else:
print(content)
finally:
if file:
file.close()
You can define your own exceptions by creating a new class that inherits from the built-in Exception class.
Example:
class CustomError(Exception):
pass
def check_value(value):
if value > 100:
raise CustomError("Value cannot be greater than 100!")
try:
check_value(150)
except CustomError as e:
print(e)
Create a custom exception called NegativeValueError and use it to validate that a user input is not negative.
class NegativeValueError(Exception):
pass
def get_positive_number():
try:
number = int(input("Enter a positive number: "))
if number < 0:
raise NegativeValueError("Number cannot be negative!")
except NegativeValueError as e:
print(e)
except ValueError:
print("Invalid input! Please enter a number.")
else:
print(f"You entered: {number}")
get_positive_number()
Write a program that asks for two numbers and performs division. Handle exceptions for invalid input and division by zero.
def safe_division():
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
except ValueError:
print("Invalid input! Please enter valid numbers.")
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(f"The result is: {result}")
safe_division()
In this comprehensive guide, we’ve covered the basics of error handling and exceptions in Python. By understanding how to handle different types of errors, you can create more robust and reliable programs. Practice these concepts with the provided examples and exercises to strengthen your understanding. Happy coding!