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 runs
Key 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.
More Related questions...