try/except in Python
Why use try/except?
Exceptions are normal in real programs:
- network failures
- missing files
- invalid user input
Instead of crashing, you can handle the problem and continue.
Basic try/except
basic_try_except.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except Exception:
print("Something went wrong")basic_try_except.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except Exception:
print("Something went wrong")This works, but itβs usually too broad.
Catch specific exceptions
specific_excepts.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except ValueError:
print("Please enter only digits.")
except ZeroDivisionError:
print("Number canβt be 0.")specific_excepts.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except ValueError:
print("Please enter only digits.")
except ZeroDivisionError:
print("Number canβt be 0.")Catch multiple exception types
multi_except.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)multi_except.py
try:
x = int(input("Enter a number: "))
print(10 / x)
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)Capture the exception object
exception_object.py
try:
int("abc")
except ValueError as e:
print("Type:", type(e))
print("Message:", e)exception_object.py
try:
int("abc")
except ValueError as e:
print("Type:", type(e))
print("Message:", e)Best practices
- Catch the narrowest exception you can.
- Donβt silently ignore exceptions.
- Log exceptions in production systems.
- Avoid
except Exception:except Exception:unless you re-raise or report clearly.
π§ͺ Try It Yourself
Exercise 1 β Catch a ValueError
Exercise 2 β Multiple Except Blocks
Exercise 3 β Raise a Custom Exception
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
