1. LPU MCA Semester 1
  2. CAB106
  3. Unit 5

CAB106 · Unit 5: Exception handling and file management

Raising exceptions, custom exceptions and assertions

12 practice questions

Key points

  • raise throws an exception; a bare raise re-raises it
  • Custom exceptions derive from Exception
  • raise ... from e records the cause
  • assert is a developer check, not input validation

raise creates an exception on purpose: raise ValueError("bad"). Only objects that derive from BaseException can be raised, so raise "error" fails with TypeError. Inside a handler a bare raise re-raises the current exception, and raise NewError(...) from e chains errors, storing the original in __cause__.

A custom exception is a class that derives from Exception (or a more specific class such as ValueError). It can add attributes:

class AgeError(ValueError):
    def __init__(self, age):
        super().__init__(f"bad age {age}")
        self.age = age

It is caught by its own class or by any parent class. print(e) shows the message while type(e).__name__ shows the class name.

assert condition, message raises AssertionError when the condition is false. Assertions are for checking internal assumptions during development and can be disabled with python -O, so they must not be used to validate user input or handle expected failures such as a missing file.

Exam trap: the message given to assert or to an exception is what print(e) shows, not the exception's class name.

Try two questions

Question 1 · Tier 3, Apply

What is the proper use of an assert statement?

  1. To replace try and except when a file cannot be opened
  2. To validate every password that a user types into a form
  3. To make a slow function run faster in production
  4. To check internal assumptions while developing, not to validate user input
Show the answer

D. Assertions document assumptions and can be disabled with the -O option.

Why not A: File errors should be handled with exceptions, not assertions.

Why not B: Assertions can be switched off, so they are unsuitable for input checks.

Why not C: Assertions do not change speed in a helpful way.

Question 2 · Tier 2, Understand

Which class should a custom exception normally derive from?

  1. The object class
  2. The str class
  3. The Exception class
  4. The list class
Show the answer

C. User-defined exceptions inherit from Exception, directly or through another exception class.

Why not A: object does not make a class usable as an exception.

Why not B: str is a text type, not an exception type.

Why not D: list is a container type, not an exception type.