try: print("I will try to print this line of code") except: print("I will print this line of code if an error is encountered")
try: print("I will try to print this line of code") except ERROR_NAME: print("I will print this line of code if error ERROR_NAME is encountered")
import sys try: S = 1/0 #Create Error except: # catch *all* exceptions e = sys.exc_info() print(e) # (Exception Type, Exception Value, TraceBack) ############ # OR # ############ try: S = 1/0 except ZeroDivisionError as e: print(e) # ZeroDivisionError('division by zero')
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong")
# Use 'try' to handle exceptions: try: code_to_try() except <exception, i.e. ValueError>: do_this() # You can add an else: or finally: statement for other branching