Q1. What is exception handling in Python?
Exception handling allows you to gracefully handle runtime errors using try, except, else, finally blocks.
It prevents program crashes.
Example:
It prevents program crashes.
Example:
try:
x = int(input("Enter number: "))
except ValueError:
print("Invalid number")Q2. What is the difference between except and except Exception?
except: catches any exception (including SystemExit, KeyboardInterrupt).
except Exception: catches all built-in exceptions except those that exit the interpreter.
It's better to catch specific exceptions or use except Exception to avoid catching system-exiting exceptions.
except Exception: catches all built-in exceptions except those that exit the interpreter.
It's better to catch specific exceptions or use except Exception to avoid catching system-exiting exceptions.
Q3. What is the purpose of else and finally in try-except?
else block runs only if no exception occurred.
finally block always runs, regardless of whether an exception occurred, used for cleanup (like closing files).
Example:
finally block always runs, regardless of whether an exception occurred, used for cleanup (like closing files).
Example:
try:
file = open(''data.txt'')
except FileNotFoundError:
print("Not found")
else:
print(file.read())
finally:
file.close()Q4. How do you raise an exception?
Use the raise keyword. You can raise built-in exceptions or custom ones.
Example:
Example:
if x < 0:
raise ValueError("x cannot be negative")Q5. What are the built-in exception types?
Common built-in exceptions: ValueError, TypeError, IndexError, KeyError, FileNotFoundError, ZeroDivisionError, ImportError, AttributeError, etc.
They are organized in a hierarchy with BaseException at the top.
They are organized in a hierarchy with BaseException at the top.
