# catch any exceptiontry: result = 10 / 0except: print("Error occurred")
# catch specific exceptiontry: result = 10 / 0except ZeroDivisionError: print("Cannot divide by zero")
# access exception detailstry: result = 10 / 0except ZeroDivisionError as e: print(f"Error: {e}")
# handle different exceptionstry: value = int(input()) result = 10 / valueexcept ValueError: print("Invalid number")except ZeroDivisionError: print("Cannot divide by zero")
# one handler for multipletry: # code passexcept (ValueError, TypeError): print("Type or value error")
# else runs if no exceptiontry: result = 10 / 2except ZeroDivisionError: print("Error")else: print("Success")
# finally always runstry: file = open("data.txt")except FileNotFoundError: print("File not found")finally: print("Cleanup")
# catch all exceptions?try: x = 1 / 0except: pass#ans: catches everything (not recommended)
# what is e?try: x = 1 / 0except ZeroDivisionError as e: type(e)#ans: ZeroDivisionError instance
# else when?try: x = 5except: print("Error")else: print("OK")#ans: "OK" (no exception)
# finally with return?def func(): try: return 1 finally: print("Finally")func()#ans: prints "Finally", returns 1
# nested try?try: try: x = 1 / 0 except ValueError: passexcept ZeroDivisionError: print("Caught")#ans: "Caught"
# multiple except order?try: x = 1 / 0except Exception: print("General")except ZeroDivisionError: print("Specific")#ans: "General" (first match wins)
# finally without except?try: x = 5finally: print("Done")#ans: valid, prints "Done"
# else without except?try: x = 5else: print("OK")#ans: SyntaxError (needs except)
# exception in finally?try: x = 5finally: y = 1 / 0#ans: raises ZeroDivisionError
# bare except position?try: x = 1 / 0except ValueError: passexcept: print("Other")#ans: "Other"
Google tag (gtag.js)