Q:

catch error data with except python

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")
40
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")
21
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')
2

  try:
  print(x)
except NameError:
  print("Variable x 
  is not defined")
except:
  print("Something else went 
  wrong") 
2
# 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
4

New to Communities?

Join the community