An exception is an abnormal situation that occurs while a program is running. It does not always mean the program must crash. With a planned handler, the program can explain the problem, record it, or continue with later logic.
Common exceptions
An exception type identifies the category of failure:
ValueErrorAn unsuitable value, such as converting "3.6" to int.
ZeroDivisionErrorDivision by zero.
IndexErrorA list index is outside its range.
KeyErrorA dictionary key is missing.
FileNotFoundErrorA requested file is missing.
AttributeErrorAn attribute does not exist.
Exceptions should not replace ordinary conditions. Use if for simple rules; exceptions fit failures discovered only while an operation runs.
KNOWLEDGE QUIZ
try, except, else, and finally
try contains operations that may fail. Once an exception occurs, remaining statements in try are skipped. Python finds a matching except and transfers control to its handler. else runs only without an exception; finally performs cleanup on either path.
Exception path debugger: from risky line to safe cleanup
Choose an input and step through execution. The highlighted line, variables, exception object, and control flow stay synchronized.
01try:02 result = a / b03except (ZeroDivisionError, TypeError) as error:04 message = type(error).__name__05else:06 message = result07finally:08 cleaned = True
1/6 · trytry:
dividend = int(input("Enter dividend: "))
divisor = int(input("Enter divisor: "))
quotient = dividend / divisor
except ValueError:
print("Only integers are supported.")
except ZeroDivisionError:
print("Divisor cannot be 0.")
else:
print("Result:", quotient)
finally:
print("This calculation is finished.")KNOWLEDGE QUIZ
Catch specific exceptions
Do not begin with an overly broad except Exception. Catching everything may swallow genuine bugs. Catch the failures expected from the current operation so the reason and response remain clear.
try:
score = int(input("Enter score: "))
except ValueError:
print("Score must be an integer.")KNOWLEDGE QUIZ
Raise an exception explicitly
raise lets a function report that input violates its requirements. The function detects the problem; its caller decides whether to explain, retry, or record it.
def normalize_score(score):
if score < 0 or score > 100:
raise ValueError("Score must be between 0 and 100.")
return score / 100
try:
ratio = normalize_score(120)
except ValueError as error:
print("Invalid input:", error)Create a Circle object safely
- Circle.__init__ raises ValueError for a negative radius.
- The main flow converts input to float and creates the object inside try.
- Catch ValueError from invalid text or a negative radius and print its message.
- Add finally so “Check finished” always prints.