Exception handling in Python allows your program to respond to unexpected errors gracefully using the try
, except
, finally
, and else
blocks.
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code that always runs, regardless of exceptions
In this structure:
try
block contains code that may raise an exception.except
block catches and handles specific exceptions.else
block runs if no exceptions were raised in the try
block.finally
block runs regardless of whether an exception occurred or not.A few of the exception types are provided in this file : exceptiontypes.html
For common exceptions official reference click official reference
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
try:
int("abc")
except (ValueError, TypeError) as e:
print(f"Error: {e}")
try:
x = 10
except:
print("Error")
else:
print("No error")
try:
f = open("file.txt")
except FileNotFoundError:
print("File not found")
finally:
print("Finished")
x = -1
if x < 0:
raise ValueError("Negative value not allowed")
class MyError(Exception):
pass
raise MyError("Something went wrong")
try:
try:
x = 1 / 0
except ZeroDivisionError:
print("Inner error")
except:
print("Outer error")
x = 5
assert x > 10, "x should be greater than 10"
try:
raise ValueError("Invalid input")
except ValueError as e:
print("Caught")
raise
import logging
try:
1 / 0
except ZeroDivisionError as e:
logging.error("Exception occurred", exc_info=True)