Friday , September 20 2024

What will be the result of executing the following code? class Ex(Exception) def __init__(self, msg): Exception.__init__(self, msg + msg) self.args = (msg,) try: raise Ex(‘ex’) except Ex as e: print(e) except Exception as e: print(e)

Questions BankCategory: Python Essentials 2What will be the result of executing the following code? class Ex(Exception) def __init__(self, msg): Exception.__init__(self, msg + msg) self.args = (msg,) try: raise Ex(‘ex’) except Ex as e: print(e) except Exception as e: print(e)
What will be the result of executing the following code?

class Ex(Exception)
    def __init__(self, msg):
        Exception.__init__(self, msg + msg)
        self.args = (msg,)
 
 
try:
    raise Ex('ex')
except Ex as e:
    print(e)
except Exception as e:
    print(e)
  • it will print exex
  • it will print ex
  • it will raise an unhandled exception
  • it will print an empty line

Explanation: Let’s analyze this code snippet:

  • First, the try block raises an Ex Exception with the ex string as its argument.
  • Then, the Ex Exception receives the ex string in the msg variable.
  • Afterwards, the replicated string msg + msg is passed on to the superclass. However, the content of the msg variable is stored in self.args.
  • Finally, the raised exception will fall under the Ex Exception. It prints the content of the e variable in the console, which is ex.

More Questions: Python Essentials 2 – Module 3 Test