loading…
CBSE Class 12 · Computer Science (083)
CBSE Class 12 Computer Science exception handling: try, except, else and finally — output questions, error-finding questions and programs, each checked by running the code.
def safe_divide():
try:
a = int(input("Numerator: "))
b = int(input("Denominator: "))
q = a / b
except ValueError:
print("Please type whole numbers only.")
except ZeroDivisionError:
print("Denominator cannot be zero.")
else:
print("Answer:", q)
finally:
print("Done.")
safe_divide()
safe_divide()
Output (typed input shown after each prompt)
Numerator: 20 Denominator: 4 Answer: 5.0 Done. Numerator: 7 Denominator: 0 Denominator cannot be zero. Done.
try:
x = int("12a")
print("converted")
except ValueError:
print("bad number")
finally:
print("finally runs")
bad number finally runs
Why: int() raises ValueError; the rest of try is skipped; finally always runs.
def divide(a, b):
try:
return a // b
except ZeroDivisionError:
return "cannot divide"
finally:
print("checked", a, b)
print(divide(9, 2))
print(divide(9, 0))
checked 9 2 4 checked 9 0 cannot divide
Why: finally runs before the function actually returns.
L = [1, 2, 3]
try:
print(L[1])
print(L[5])
print("unreached")
except IndexError as e:
print("IndexError:", e)
else:
print("no error")
2 IndexError: list index out of range
Why: else runs only when try raised nothing.
try:
n = int("x")
except ValueError
print("Invalid")
Running it stops with SyntaxError.
try:
n = int("x")
except ValueError:
print("Invalid")
PyRun is not affiliated with CBSE. Questions are written in the board's style for practice; they are not past papers.