To raise your own exception use the raise method:
raise ValueError('That value not so good')Here's the documentation on the available exception classes
Like other languages, Python has a try construct:
try:
raise NameError('Bad name')
except NameError:
print('Got a name error')
raiseYou can also pass the error message:
try:
raise NameError('Bad name')
except NameError as err:
print('Got a name error: "{}"'.format(err))You can also catch other errors with a final, catchall except:
import sys
try:
raise ValueError('Bad value')
except NameError as err:
print('Got a name error: "{}"'.format(err))
except:
print('Got some other error: "{}"'.format(sys.exc_info()[0]))You can execute code if not exceptions are raised with and else:
try:
pass
except NameError as err:
print('Got a name error: "{}"'.format(err))
else:
print('No exception raised')You can execute followup code whether or not an exception is raised with finally:
try:
pass
except NameError as err:
print('Got a name error: "{}"'.format(err))
finally:
print('Always executing this code')