Python Error Handling with try-except and raise Statements
Using try-except and raise for Input Validation
try:
gender = input("Enter your gender: ")
if gender.lower() not in ["male", "female"]:
raise ValueError("Input must be 'male' or 'female'")
print("Your gender is:", gender)
except ValueError as e:
print(e)
except Exception:
print("An unexpected error occurred")
Example Output:
Enter your gender: other Input must be 'male' or 'female'
or
Enter your gender: female Your gender is: female
Handling Arithmetic Exceptions
try:
val1 = float(input("Enter first number: "))
val2 = float(input("Enter second number: "))
quotient = val1 / val2
print(quotient)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid numeric input")
except Exception:
print("An unexpected error occurred")
Example Output:
Enter first number: 10 Enter second number: 0 Cannot divide by zero
or
Enter first number: 10 Enter second number: abc Invalid numeric input
or
Enter first number: 10 Enter second number: 2 5.0
Using else and final Blocks
try:
x = float(input("Enter numerator: "))
y = float(input("Enter denominator: "))
result = x / y
except ZeroDivisionError:
print("Division by zero error")
except ValueError:
print("Invalid number format")
except Exception:
print("General error")
else:
print("Division result:", result)
finally:
print("Operation complete")
Example Output:
Enter numerator: 10 Enter denominator: abc Invalid number format Operation complete
or
Enter numerator: 10 Enter denominator: 2 Division result: 5.0 Operation complete
Basic Debugging with Breakpoints
counter = 1
while counter < 5:
print(counter)
counter += 1