Bird
Raised Fist0

Which of the following functions correctly catches any exception and prints its message in Python?

hard🚀 Application Q8 of Q15
Python - Exception Handling Fundamentals
Which of the following functions correctly catches any exception and prints its message in Python?
Adef func(): try: pass except Exception: print('Error')
Bdef func(): try: pass except: print('Error')
Cdef func(): try: pass except Exception as e: print(e)
Ddef func(): try: pass except e: print(e)
Step-by-Step Solution
Solution:
  1. Step 1: Catch Exception with Variable

    To print the error message, the exception must be caught as a variable using except Exception as e:.
  2. Step 2: Analyze Options

    def func(): try: pass except Exception as e: print(e) correctly catches the exception as e and prints it. def func(): try: pass except: print('Error') uses bare except without variable. def func(): try: pass except Exception: print('Error') catches exception but does not capture the message. def func(): try: pass except e: print(e) uses invalid syntax except e:.
  3. Final Answer:

    def func(): try: pass except Exception as e: print(e) is correct.
  4. Quick Check:

    Use 'except Exception as e' to access error message [OK]
Quick Trick: Use 'except Exception as e' to print error [OK]
Common Mistakes:
MISTAKES
  • Using bare except without variable
  • Not capturing exception as variable
  • Incorrect except syntax like 'except e:'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes