Notice: Due to an ongoing migration of our storage and publishing system, material requested since last month will not be uploaded for the time being, and new requests are paused. All existing notes remain available.

Unit 5 MCQs Exception handling

ECAP776 60 questions. Pick an option to check it.

Read the notes Subjective questions

0 of 60 answered 0 right 0 wrong , 60 left

  1. Question 1 of 60 Catching exceptions Easy

    Which Python block contains code that might cause an exception?

  2. Question 2 of 60 Catching exceptions Easy

    Which exception is raised when a number is divided by zero?

  3. Question 3 of 60 Catching exceptions Easy

    Which block normally runs whether or not an exception occurs?

  4. Question 4 of 60 Catching exceptions Easy

    When does the else block of a try statement run?

  5. Question 5 of 60 Catching exceptions Easy

    In except ValueError as error:, what does error represent?

  6. Question 6 of 60 Catching multiple exceptions Easy

    Which syntax catches both ValueError and TypeError in one handler?

  7. Question 7 of 60 Catching multiple exceptions Easy

    How can different exception types be given different handling code?

  8. Question 8 of 60 Catching multiple exceptions Easy

    When catching related exception classes, which handler should usually appear first?

  9. Question 9 of 60 Catching multiple exceptions Easy

    If several except blocks could match an exception, which matching block runs?

  10. Question 10 of 60 Catching multiple exceptions Easy

    Which statement correctly handles either a conversion error or an invalid operand type?

  11. Question 11 of 60 Raising exceptions Easy

    Which keyword is used to deliberately trigger an exception in Python?

  12. Question 12 of 60 Raising exceptions Easy

    Which statement raises a built-in ValueError?

  13. Question 13 of 60 Raising exceptions Easy

    What does a bare raise statement do inside an except block?

  14. Question 14 of 60 Raising exceptions Easy

    Why might a function explicitly raise an exception?

  15. Question 15 of 60 Raising exceptions Easy

    Which statement raises an exception with the message Age cannot be negative?

  16. Question 16 of 60 Custom exception Easy

    Which built-in class should a basic custom exception normally inherit from?

  17. Question 17 of 60 Custom exception Easy

    Which definition correctly creates a custom exception named InvalidAgeError?

  18. Question 18 of 60 Custom exception Easy

    How is a custom exception named InvalidAgeError triggered?

  19. Question 19 of 60 Custom exception Easy

    Which handler catches a custom exception named InvalidAgeError?

  20. Question 20 of 60 Custom exception Easy

    What is a main benefit of defining a custom exception?

  21. Question 21 of 60 Catching exceptions Medium

    What is printed by the following code?

    Python
    def parse_value(text):
        try:
            return int(text)
        except ValueError:
            return -1
    
    print(parse_value("3.5"))

  22. Question 22 of 60 Catching exceptions Medium

    What is the output of this code?

    Python
    try:
        result = 10 // 2
    except ZeroDivisionError:
        print("error")
    else:
        print(result)
    finally:
        print("done")

  23. Question 23 of 60 Catching exceptions Medium

    What is printed by the exception handler?

    Python
    try:
        int("python")
    except ValueError as err:
        print(type(err).__name__)

  24. Question 24 of 60 Catching exceptions Medium

    What is the output of the following function call?

    Python
    def calculate():
        try:
            return 8 / 0
        except ZeroDivisionError:
            return 2
        finally:
            print("cleanup")
    
    print(calculate())

  25. Question 25 of 60 Catching exceptions Medium

    What happens when this code is executed?

    Python
    try:
        int("x")
    except ValueError:
        print("conversion failed")
        10 / 0

  26. Question 26 of 60 Catching multiple exceptions Medium

    Which handler correctly catches either ValueError or TypeError and stores the exception in err?

  27. Question 27 of 60 Catching multiple exceptions Medium

    Assume missing.txt does not exist. Which handler runs?

    Python
    try:
        open("missing.txt")
    except OSError:
        print("OS")
    except FileNotFoundError:
        print("FILE")

  28. Question 28 of 60 Catching multiple exceptions Medium

    What does the following code print?

    Python
    def convert(value):
        try:
            int(value)
        except (TypeError, ValueError):
            return "bad"
        return "ok"
    
    print(convert(None), convert("7"))

  29. Question 29 of 60 Catching multiple exceptions Medium

    What is printed by this code?

    Python
    try:
        value = 4 / 0
    except ArithmeticError:
        print("arithmetic")
    except ZeroDivisionError:
        print("zero")

  30. Question 30 of 60 Catching multiple exceptions Medium

    What happens when this code runs?

    Python
    try:
        data = {}
        print(data["name"])
    except (ValueError, TypeError):
        print("handled")

  31. Question 31 of 60 Raising exceptions Medium

    Which statement should replace the comment to reject a negative quantity with an appropriate built-in exception?

    Python
    def set_quantity(quantity):
        if quantity < 0:
            # replacement
        return quantity

  32. Question 32 of 60 Raising exceptions Medium

    What occurs when load() is called?

    Python
    def load():
        try:
            int("invalid")
        except ValueError:
            print("logged")
            raise
    
    load()

  33. Question 33 of 60 Raising exceptions Medium

    After the following handler raises RuntimeError, what is stored in the new exception's __cause__ attribute?

    Python
    try:
        int("x")
    except ValueError as err:
        raise RuntimeError("conversion failed") from err

  34. Question 34 of 60 Raising exceptions Medium

    Given the following class, what does raise Failure do?

    Python
    class Failure(Exception):
        pass
    
    raise Failure

  35. Question 35 of 60 Raising exceptions Medium

    What is the main effect of from None in this code?

    Python
    try:
        1 / 0
    except ZeroDivisionError:
        raise ValueError("invalid result") from None

  36. Question 36 of 60 Custom exception Medium

    What is printed by this code?

    Python
    class AgeError(Exception):
        pass
    
    def register(age):
        if age < 0:
            raise AgeError("invalid age")
    
    try:
        register(-2)
    except Exception as err:
        print(type(err).__name__)

  37. Question 37 of 60 Custom exception Medium

    What does this code print?

    Python
    class ScoreError(Exception):
        def __init__(self, score):
            self.score = score
            super().__init__(f"score={score}")
    
    try:
        raise ScoreError(120)
    except ScoreError as err:
        print(err.score, str(err))

  38. Question 38 of 60 Custom exception Medium

    Which handler catches the exception raised below?

    Python
    class ValidationError(Exception):
        pass
    
    class EmailError(ValidationError):
        pass
    
    raise EmailError("invalid email")

  39. Question 39 of 60 Custom exception Medium

    What is the value of err.args in the handler?

    Python
    class LimitError(Exception):
        def __init__(self, limit):
            self.limit = limit
            super().__init__(f"limit={limit}")
    
    try:
        raise LimitError(5)
    except LimitError as err:
        print(err.args)

  40. Question 40 of 60 Custom exception Medium

    What is printed when withdraw(80, 50) is called?

    Python
    class InsufficientFundsError(Exception):
        def __init__(self, shortage):
            self.shortage = shortage
            super().__init__("insufficient funds")
    
    def withdraw(amount, balance):
        if amount > balance:
            raise InsufficientFundsError(amount - balance)
        return balance - amount
    
    try:
        print(withdraw(80, 50))
    except InsufficientFundsError as err:
        print(err.shortage)

  41. Question 41 of 60 Catching exceptions Hard

    What is printed by the following code?

    Python
    events = []
    try:
        try:
            events.append('try')
        except ValueError:
            events.append('inner')
        else:
            events.append('else')
            raise KeyError('missing')
        finally:
            events.append('finally')
    except KeyError:
        events.append('outer')
    
    print(events)

  42. Question 42 of 60 Catching exceptions Hard

    What does f() return?

    Python
    def f():
        try:
            raise ValueError('bad')
        except ValueError:
            return 'handled'
        finally:
            return 'final'

  43. Question 43 of 60 Catching exceptions Hard

    What happens when this code executes?

    Python
    err = 'outer'
    try:
        raise ValueError('inner')
    except ValueError as err:
        saved = str(err)
    
    print(err, saved)

  44. Question 44 of 60 Catching exceptions Hard

    What is the result of this code?

    Python
    class Manager:
        def __enter__(self):
            return self
    
        def __exit__(self, exc_type, exc, tb):
            return 'False'
    
    with Manager():
        raise RuntimeError('failure')
    
    print('done')

  45. Question 45 of 60 Catching exceptions Hard

    What occurs when this code runs?

    Python
    try:
        raise KeyboardInterrupt()
    except Exception:
        print('caught')
    finally:
        print('cleanup')

  46. Question 46 of 60 Catching multiple exceptions Hard

    What is printed by the following code?

    Python
    try:
        raise TypeError('wrong type')
    except ValueError or TypeError:
        print('first')
    except Exception:
        print('fallback')

  47. Question 47 of 60 Catching multiple exceptions Hard

    What happens in this example?

    Python
    try:
        raise KeyError('key')
    except (KeyError, IndexError):
        raise ValueError('converted')
    except ValueError:
        print('second handler')

  48. Question 48 of 60 Catching multiple exceptions Hard

    What is printed?

    Python
    class ParseError(Exception):
        pass
    
    class DetailedParseError(ParseError):
        pass
    
    try:
        raise DetailedParseError()
    except (ParseError, ValueError):
        print('general')
    except DetailedParseError:
        print('detailed')

  49. Question 49 of 60 Catching multiple exceptions Hard

    In Python 3.11 or later, what is printed by this code?

    Python
    events = []
    try:
        raise ExceptionGroup(
            'group',
            [ValueError('a'), TypeError('b'), ValueError('c')]
        )
    except* ValueError as group:
        events.append(('values', len(group.exceptions)))
    except* Exception as group:
        events.append(('rest', len(group.exceptions)))
    
    print(events)

  50. Question 50 of 60 Catching multiple exceptions Hard

    In Python 3.11 or later, what happens when this code is parsed?

    Python
    try:
        operation()
    except ValueError:
        recover()
    except* TypeError:
        recover_group()

  51. Question 51 of 60 Raising exceptions Hard

    What exception results from executing raise when no exception is currently being handled?

    Python
    def reroute():
        raise
    
    reroute()

  52. Question 52 of 60 Raising exceptions Hard

    What is printed by this code?

    Python
    class SignalError(Exception):
        pass
    
    try:
        raise SignalError
    except SignalError as exc:
        print(exc.args)

  53. Question 53 of 60 Raising exceptions Hard

    Which values are printed in Python 3 by this code?

    Python
    try:
        1 / 0
    except ZeroDivisionError:
        try:
            raise ValueError('invalid') from None
        except ValueError as exc:
            print(
                type(exc.__context__).__name__,
                exc.__cause__,
                exc.__suppress_context__
            )

  54. Question 54 of 60 Raising exceptions Hard

    What is printed by the outer handler?

    Python
    try:
        try:
            raise ValueError('primary')
        finally:
            raise TypeError('cleanup')
    except Exception as exc:
        print(type(exc).__name__, type(exc.__context__).__name__)

  55. Question 55 of 60 Raising exceptions Hard

    How do the tracebacks produced by these functions differ?

    Python
    def bare():
        try:
            1 / 0
        except Exception:
            raise



    def named():
    try:
    1 / 0
    except Exception as exc:
    raise exc

  56. Question 56 of 60 Custom exception Hard

    What occurs when this custom exception is raised?

    Python
    class Shutdown(BaseException):
        pass
    
    try:
        raise Shutdown()
    except Exception:
        print('caught')
    finally:
        print('cleanup')

  57. Question 57 of 60 Custom exception Hard

    What does the following code print?

    Python
    class HttpError(Exception):
        def __init__(self, status):
            self.status = status
            super().__init__(f'status={status}')
    
    exc = HttpError(404)
    print(exc.args, str(exc), exc.status)

  58. Question 58 of 60 Custom exception Hard

    What is printed by this code?

    Python
    class CodeError(Exception):
        def __init__(self, code):
            self.code = code
            super().__init__(code)
    
    try:
        raise CodeError
    except CodeError:
        print('code')
    except TypeError:
        print('type')

  59. Question 59 of 60 Custom exception Hard

    What is printed by the outer handler?

    Python
    class BrokenMessage(Exception):
        def __str__(self):
            raise RuntimeError('formatting failed')
    
    try:
        try:
            raise BrokenMessage()
        except BrokenMessage as exc:
            print(exc)
    except RuntimeError as exc:
        print(type(exc.__context__).__name__)

  60. Question 60 of 60 Custom exception Hard

    What is printed after the exception's args attribute is reassigned?

    Python
    class PairError(Exception):
        def __init__(self, left, right):
            self.left = left
            self.right = right
            super().__init__(left, right)
    
    exc = PairError('a', 'b')
    exc.args = ('x',)
    print(str(exc), exc.left, exc.right)

That's unit 5

Answer a few questions and your score shows up here.