Exception_Handling_Python
Exception_Handling_Python
Exception handling in Python is a way to handle errors or exceptions that occur during program
execution, preventing the program from crashing. It allows developers to handle unexpected
situations gracefully using try, except, else, and finally blocks.
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a number.")
except Exception as e:
print("An unexpected error occurred:", e)
else:
print("No errors occurred.")
finally:
print("Execution completed.")
Handling ZeroDivisionError
try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
Handling ValueError
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter an integer.")