try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful, result is:", result)
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
file.close()
print("File has been closed")
try:
result = int("abc")
except ValueError as e:
print(f"An error occurred: {e}")
try:
result = int("not a number")
except ValueError as e:
print("Handling exception...")
raise
try:
result = 10 / 0
except Exception as e:
print(f"An unexpected error occurred: {e}")
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom exception")
except CustomError as e:
print(f"Caught custom exception: {e}")
numbers = [10, 0, 5, 'a']
for num in numbers:
try:
result = 10 / num
print(f"10 divided by {num} is {result}")
except (ZeroDivisionError, TypeError) as e:
print(f"Error: {e}")
while True:
try:
age = int(input("Enter your age: "))
break
except ValueError:
print("Please enter a valid integer.")
try:
with open("nonexistent_file.txt", "r") as file:
content = file.read()
except IOError as e:
print(f"File error: {e}")
try:
result = 10 / 2
except ZeroDivisionError:
print("Error occurred")
finally:
print("This will always execute, regardless of errors")
try:
result = 10 / 2
result = int("abc")
except ValueError:
print("ValueError occurred")
except ZeroDivisionError:
print("ZeroDivisionError occurred")
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Value error occurred")
try:
try:
result = 10 / 0
except ZeroDivisionError:
print("Inner block: Division by zero")
except Exception:
print("Outer block: General exception")
try:
result = int("not a number")
except ValueError:
print("Handling ValueError")
except (TypeError, KeyError):
pass # Ignore TypeError and KeyError
try:
with open("example.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found")
import logging
logging.basicConfig(level=logging.ERROR)
try:
result = 10 / 0
except ZeroDivisionError as e:
logging.error("An error occurred: %s", e)
def divide_numbers(a, b):
try:
return a / b
except ZeroDivisionError:
print("Handled in function")
raise
try:
result = divide_numbers(10, 0)
except ZeroDivisionError:
print("Handled in caller")
import threading
def thread_func():
try:
result = 10 / 0
except ZeroDivisionError:
print("Exception in thread")
thread = threading.Thread(target=thread_func)
thread.start()
thread.join()
import asyncio
async def async_func():
try:
result = 10 / 0
except ZeroDivisionError:
print("Exception in async function")
asyncio.run(async_func())
try:
result = 10 / 2
finally:
print("This block always executes, even if there was an exception")