“Python attrape toutes les exceptions” Réponses codées

Comment imprimer une erreur dans Try Sauf Python

try:
  # some code
except Exception as e:
	print("ERROR : "+str(e))
Jenova

Python attrape toutes les exceptions

try:
    raise Exception("Oh no! An error happened!")
except Exception as err:
    print("An error was handled")
finally:
  	print("This runs either way.")
Mattalui

Catch des données d'erreur avec sauf Python

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')
Cheerful Caracal

Python attraper des exceptions

# import module sys to get the type of exception
import sys

randomList = ['x', 0, 4]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print(e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
Outrageous Ostrich

Attraper des exceptions à Python

# import module sys to get the type of exception
import sys

randomList = ['x', 0, 4]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except:
        print(sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
Outrageous Ostrich

Réponses similaires à “Python attrape toutes les exceptions”

Questions similaires à “Python attrape toutes les exceptions”

Plus de réponses similaires à “Python attrape toutes les exceptions” dans Python

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code