Aug 8, 2024
print("Hello, world"
(missing closing quote)SyntaxError: unterminated string literal
x = int(input("What's x? "))
print(f"x is {x}")
ValueError: invalid literal for int() with base 10: 'cat'
try
and except
keywords to handle errors:
try:
x = int(input("What's x? "))
except ValueError:
print("x is not an integer")
try
is attempted.except
block executes only if an error occurs.while True:
try:
x = int(input("What's x? "))
break
except ValueError:
print("x is not an integer")
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Not an integer!")
x = get_int("What's x? ")
print(f"x is {x}")
def get_int(prompt):
# code...
raise
keyword.Errors are inevitable in programming, but knowing how to handle them is essential:
Understanding and using exceptions will enhance your programming skills.