Why do programmers create custom exceptions instead of using only built-in exceptions?
Think about how specific error messages help understand problems better.
Custom exceptions help programmers signal specific problems that built-in exceptions don't cover. This makes debugging and handling errors clearer and easier.
What will be the output of this code?
class MyError(Exception): pass try: raise MyError('Oops!') except MyError as e: print(f'Caught custom error: {e}') except Exception: print('Caught general error')
Look at which exception is raised and which except block catches it.
The code raises a custom exception MyError, which is caught by the except MyError block, printing the message with the error text.
What will be printed when this code runs?
class ErrorA(Exception): pass class ErrorB(Exception): pass def test_error(e): try: raise e except ErrorA: print('Caught ErrorA') except ErrorB: print('Caught ErrorB') except Exception: print('Caught general exception') test_error(ErrorB('error'))
Check which exception is raised and which except block matches it first.
The function raises ErrorB, which is caught by the except ErrorB block, printing 'Caught ErrorB'.
Which of these is NOT a good reason to create custom exceptions?
Think about the purpose of custom exceptions in teamwork and code clarity.
Custom exceptions are meant to improve clarity and error handling, not to confuse or complicate code unnecessarily.
What is the output of this code?
class BaseError(Exception): pass class ChildError(BaseError): pass try: raise ChildError('child error occurred') except BaseError as e: print(f'Caught base error: {e}') except ChildError: print('Caught child error')
Remember that except blocks are checked in order and inheritance matters.
The ChildError is a subclass of BaseError. The first except block matches it and prints the message.