Exceptions

Common Exceptions - ValueError

  1. # ValueError - invalid value
  2. try:
  3. int("abc")
  4. except ValueError:
  5. print("Cannot convert to int")

Common Exceptions - TypeError

  1. # TypeError - wrong type
  2. try:
  3. "2" + 2
  4. except TypeError:
  5. print("Type mismatch")

Common Exceptions - KeyError

  1. # KeyError - missing key
  2. try:
  3. d = {"a": 1}
  4. value = d["b"]
  5. except KeyError:
  6. print("Key not found")

Common Exceptions - IndexError

  1. # IndexError - invalid index
  2. try:
  3. lst = [1, 2, 3]
  4. value = lst[10]
  5. except IndexError:
  6. print("Index out of range")

Common Exceptions - AttributeError

  1. # AttributeError - no attribute
  2. try:
  3. x = 5
  4. x.append(1)
  5. except AttributeError:
  6. print("Attribute not found")

File Exceptions

  1. # FileNotFoundError
  2. try:
  3. with open("missing.txt") as f:
  4. pass
  5. except FileNotFoundError:
  6. print("File not found")
  7. #ans: PermissionError
  8. try:
  9. with open("/root/file.txt", "w") as f:
  10. pass
  11. except PermissionError:
  12. print("Permission denied")

Raising Exceptions

  1. # raise an exception
  2. def validate_age(age):
  3. if age < 0:
  4. raise ValueError("Age cannot be negative")
  5. return age

Re-raising Exceptions

  1. # re-raise same exception
  2. try:
  3. result = 10 / 0
  4. except ZeroDivisionError:
  5. print("Logging error...")
  6. raise

Exercises - Part 1

  1. # ValueError when?
  2. int("3.14")
  3. #ans: ValueError

Exercises - Part 2

  1. # TypeError example?
  2. len(5)
  3. #ans: TypeError (int has no len)

Exercises - Part 3

  1. # KeyError vs get?
  2. d = {"a": 1}
  3. d["b"]
  4. #ans: KeyError
  5. d.get("b")
  6. #ans: None

Exercises - Part 4

  1. # IndexError negative?
  2. lst = [1, 2]
  3. lst[-10]
  4. #ans: IndexError

Exercises - Part 5

  1. # NameError?
  2. print(undefined_variable)
  3. #ans: NameError

Exercises - Part 6

  1. # ZeroDivisionError?
  2. 5 / 0
  3. #ans: ZeroDivisionError
  4. 5 // 0
  5. #ans: ZeroDivisionError

Exercises - Part 7

  1. # raise with message?
  2. raise ValueError("Custom message")
  3. #ans: raises with message

Exercises - Part 8

  1. # raise without exception?
  2. try:
  3. raise
  4. except:
  5. pass
  6. #ans: RuntimeError (no active exception)

Exercises - Part 9

  1. # exception hierarchy?
  2. try:
  3. x = 1 / 0
  4. except Exception:
  5. print("Caught")
  6. #ans: catches ZeroDivisionError

Exercises - Part 10

  1. # assert raises what?
  2. assert False, "Message"
  3. #ans: AssertionError: Message

Google tag (gtag.js)