Exceptions

Exceptions represent error conditions that interrupt normal control flow. Python code can raise, catch, and define exceptions.

Handling Exceptions

try:
    print(1 / x[ind])
except ZeroDivisionError:
    print("Cannot divide by zero!")
except IndexError:
    print("Index out of range!")

Catch specific exceptions when possible. Broad exception handlers hide bugs.

Raising Exceptions

if new_bal < 0:
    raise ValueError("Invalid balance!")

After raise, the function stops unless the exception is caught somewhere up the call stack.

Custom Exceptions

class SalaryError(ValueError):
    pass
 
class BonusError(SalaryError):
    pass

Custom exceptions make error intent clearer.

Exception Inheritance

An except block for a parent exception catches child exceptions too.

try:
    emp.give_bonus(7000)
except SalaryError:
    print("SalaryError caught")
except BonusError:
    print("BonusError caught")

In this order, BonusError will never run because BonusError inherits from SalaryError.

Correct order:

try:
    emp.give_bonus(7000)
except BonusError:
    print("BonusError caught")
except SalaryError:
    print("SalaryError caught")

Rule: catch child exceptions before parent exceptions.