SimpleTuts.com

Python Try Except

In Python, the `try` block allows you to execute code that might throw an exception, and the `except` block lets you handle specific errors that occur within the `try` block, ensuring your program can gracefully recover from exceptions.


try:
  print(x)
except:
  print("An exception occurred")
                
Python Online Compiler

Using finally block


try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")
                
Python Online Compiler

Many Exceptions


try:
  x=10/0
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")
                
Python Online Compiler