?print-pdf
' Created for
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to handle the specific exception
print("Cannot divide by zero!")
print("hello)
can not be handled, as they occur in parsing stage, i.e. before the code is executed.
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the specific exception
else:
# Code that should run only if the try block was successful
finally:
# Always executes, regardless of whether an exception occurred
# (useful for cleaning up resources such as closing files or network connections)
except
block.ZeroDivisionError
, FileNotFoundError
).try
block. It is useful for code that should run when everything goes as expected.
try:
# Code which can raise an exception
user_number = int(input("Enter a number: "))
except ValueError:
# This block will execute if the user input cannot be converted to an integer
# (e.g., if a non-numeric value is entered)
print("You did not enter a number!")
except Exception as e:
# This block will execute if any other unexpected error occurs
print(f"An unexpected error occurred: {e}")
else:
# This block will execute only if no exception was raised in the try block
print("Your number is ", user_number)
finally:
# This block will always execute, regardless of whether an exception occurred or not
print("Cleanup...")
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
# This block will execute if any other unexpected error occurs
print(f"An unexpected error occurred: {e}")
try:
number = int(input("Enter a number: "))
except ValueError:
print("That's not a valid number!")
else:
# This runs only if no exceptions occurred
print(f"You entered: {number}")
try:
# Try to read file
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
finally:
# This runs whether an exception occurred or not
# Great for cleanup operations
file.close() if 'file' in locals() else None
raise
statementraise
statement:raise
an ExceptionType to be raised
def get_user_age():
while True:
try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age must be between 1 and 99")
return age
except ValueError:
print("Please enter a valid age.")
user_age = get_user_age()
# Continue with your program using the valid age
print(f"You are {user_age} years old.")
raise
statement to trigger custom errors when necessary.Exception
class:
# define custom exception
class UserNameError(Exception):
"""Raised when a username is less than 3 characters long."""
def __init__(self, username):
super().__init__(
f"Username '{username}' is too short (must be at least 3 characters)"
)
try:
user_name = input("Enter your name: ")
if len(user_name) < 3:
raise UserNameError(user_name)
except UserNameError as e:
print(e)
except Exception as e:
print(f"Oops! Something went wrong! ({e})")
### Example usage
# Enter your name: ab
# Username 'ab' is too short (must be at least 3 characters)
These slides are based on
customised version of
framework