Python / Core Python Fundamentals Interview Questions
How does exception handling work in Python using try/except?
Python uses a try/except block to catch and handle exceptions rather than crashing the program. Code that might raise an error goes inside try; the handler goes inside except.
try:
result = int(input('Enter a number: '))
print(100 / result)
except ValueError:
print('Not a valid integer.')
except ZeroDivisionError:
print('Cannot divide by zero.')
except Exception as e:
print(f'Unexpected error: {e}')
else:
print('Calculation succeeded.') # runs only if no exception
finally:
print('Always runs — good for cleanup.') # always runsKey rules: always catch the most specific exception first, broad ones last. Catching bare Exception is acceptable as a last resort, but catching BaseException is usually wrong because it swallows KeyboardInterrupt and SystemExit.
The else clause runs only when no exception was raised — a clean place to put code that should only execute on success. The finally clause always runs regardless of whether an exception occurred, making it the right place for cleanup (closing a file, releasing a lock).
You can raise your own exceptions with raise ValueError('message') and create custom exception classes by subclassing Exception. Re-raise a caught exception inside an except block with bare raise to preserve the original traceback.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
