Learn how to handle Python errors and exceptions effectively. Fix common Python errors like SyntaxError, TypeError, and NameError with practical examples.
Exception Handling in Python. Exception handling is crucial for making your code more robust and preventing it from crashing due to unexpected errors.
try, except block to handle exceptions.try block, and the except block contains code to handle the error if it occurs.Example:
try:
x = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
except blocks. try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("That's not a valid number!")
else Blockelse block runs if no exceptions are raised in the try block. try:
num = int(input("Enter a number: "))
print(f"Success! You entered {num}.")
except ValueError:
print("Invalid input!")
else:
print("No exceptions occurred.")
finally Blockfinally block runs no matter what, whether or not an exception was raised. It’s often used for cleanup tasks (e.g., closing files or releasing resources).Example:
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing the file.")
file.close() # This will always execute
raise keyword. This can be useful for custom error handling.Example:
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older.")
else:
print("Age is valid.")
try:
check_age(15)
except ValueError as e:
print(f"Error: {e}")
Exception class.Example:
class NegativeNumberError(Exception):
pass
def check_number(num):
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
else:
print("Number is valid.")
try:
check_number(-5)
except NegativeNumberError as e:
print(f"Error: {e}")
ValueError (non-numeric input) and ZeroDivisionError (division by zero).TooYoungError that is raised if a user enters an age below 18. Handle this exception in the program.Would you like to try these exercises, or would you like to explore another topic such as file handling with exceptions, or more about the try, except blocks?
else Block After try Without exceptCode:
try:
result = 10 / 2
else:
print("Division successful!")
Mistake:
An else block is used incorrectly after try without an except block.
Corrected Code:
try:
result = 10 / 2
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division successful!")
else block runs only if no exception occurs.Answer Key (True/False):
What is the correct way to raise an exception in Python? a) raise Exception(“error message”) b) throw Exception(“error message”) c) exit(“error message”) d) halt(“error message”)