Use exception handling to prevent your program from crashing when unexpected errors occur.
Exception Handling is a method in Python used to handle errors during program execution. It helps the program continue running instead of stopping suddenly.
try:
number = 10 / 0
except:
print("Cannot divide by zero")
try:
age = int(input("Enter age: "))
except ValueError:
print("Please enter a number")
The finally block always executes whether an error occurs or not.
try:
print("Opening file")
finally:
print("Program finished")
age = -5
if age < 0:
raise Exception("Age cannot be negative")
An exception is an error that occurs while running a program.
Python uses try, except, finally and raise keywords.
Yes, it makes programs safer and more reliable.