What is exception handling
In : MSc IT Subject : Python ProgrammingException handling is a programming mechanism that allows programs to gracefully handle and recover from unexpected errors or exceptional situations that occur during program execution. Instead of crashing when an error occurs, the program can catch the error, handle it appropriately, and continue running or terminate gracefully.
Example :
# Without exception handling
def divide(a, b):
return a / b
# This will crash the program
# result = divide(10, 0) # ZeroDivisionError
# With exception handling
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
result = safe_divide(10, 0) # Prints error message, returns None
print("Program continues running...")