Friday , September 20 2024

What is the expected result of the following snippet? try: raise Exception except BaseException: print(“a”) except Exception: print(“b”) except: print(“c”)

Questions BankCategory: Python Essentials 2What is the expected result of the following snippet? try: raise Exception except BaseException: print(“a”) except Exception: print(“b”) except: print(“c”)
What is the expected result of the following snippet?

try:
    raise Exception
except BaseException:
    print("a")
except Exception:
    print("b")
except:
    print("c")
  • a
  • b
  • 1
  • an error message

Explanation: Because the raise Exception statement in the try branch raises an exception on demand, the exception is handled by one of the except branches.

Even though Exception is a more concrete exception class than BaseException, because the order of branches matters, the exception is handled by the first matching except branch, which is except BaseException. The code in the example is an example of bad practice – you should not put more general exceptions before more concrete ones.

More Questions: Python Essentials 2 (PE2) Course Final Test