Error handling in Python is a way to gracefully manage exceptions (errors) that occur during program execution so that your program does not crash unexpectedly. Instead of stopping the program, you can catch errors, show user-friendly messages, and optionally recover from the problem.
try block.The general structure of error handling in Python uses try, except, else, and finally blocks:
try:
# code that might raise an exception
risky_operation()
except SpecificErrorType:
# handle a specific error
handle_error()
except AnotherErrorType:
# handle another error
handle_another_error()
else:
# runs only if no exception was raised
run_if_no_error()
finally:
# always runs (cleanup)
cleanup()
Use try to wrap code that may raise an exception and except to handle it.
try:
# attempt a division operation
x = 10 / 0
except ZeroDivisionError:
# handle division by zero gracefully
print("Cannot divide by zero!")
You can catch multiple types of errors in separate except blocks.
try:
# convert string to integer
num = int("abc")
# perform division with the converted number
result = 10 / num
except ValueError:
# handle invalid integer conversion
print("Invalid conversion to integer")
except ZeroDivisionError:
# handle division by zero
print("Division by zero error")
Catch any exception using except Exception as e and get the error message. Use this carefully, because it can hide specific bugs if overused.
try:
# code that may raise any kind of exception
x = 10 / 0
except Exception as e:
# catch all exceptions and print the message
print("Error occurred:", e)
else runs if no exception occurs; finally always runs, whether an error occurred or not.
try:
# try to divide two numbers
num = 10 / 2
except ZeroDivisionError:
# handle division by zero
print("Error!")
else:
# runs only if no exception occurred
print("Division successful")
finally:
# code that always runs
print("This always runs")
You can raise exceptions manually using raise when a condition is not satisfied.
def check_age(age):
# validate that age meets minimum requirement
if age < 18:
# raise an error if age is too low
raise ValueError("Age must be 18 or older")
# return True when age is valid
return True
try:
# call the validation function with an invalid age
check_age(15)
except ValueError as e:
# handle the validation error
print("Error:", e)
Cannot divide by zero! because dividing by zero raises ZeroDivisionError.int("abc") raises ValueError → prints Invalid conversion to integer.Error occurred: division by zero.Division successful then This always runs.check_age(15) raises ValueError → prints Error: Age must be 18 or older.ValueError, ZeroDivisionError) rather than using a bare except:.try block as small as possible so it is easy to locate the source of an error.finally for code that must run (e.g., closing files or releasing resources).raise to enforce conditions and signal invalid states in your code.Exception unless you really need a global handler (and still log the error).try-except.try-except and print a message if the conversion fails.ValueError when a user enters a negative age or marks.except blocks to handle both ValueError and ZeroDivisionError in one program.try block and use finally to ensure the file is closed.