python Custom exception instance detail

  • 2020-06-12 09:32:05
  • OfStack

python Custom exception instance detail

This article explains Python custom exceptions in two ways: first, create a new exception class to own the exception, and second, raise's only 1 argument specifies the exception to be thrown

1. You can have your own exceptions by creating a new exception class. Exceptions should inherit from the Exception class, either directly or indirectly.


>>>raiseNameError('HiThere')
Traceback(most recent call last):
File"<pyshell#45>", line 1,in<module>
raiseNameError('HiThere')
NameError:HiThere

2. The only argument to raise 1 specifies the exception to be thrown. It must be an instance of an exception or a class of the exception (a subclass of Exception).

If you just want to know if this throws an exception and don't want to handle it, a simple raise statement can throw it again.


>>>classMyError(Exception):
def __init__(self, value):
      self.value = value
def __str__(self):
return repr(self.value)
>>>try:
raiseMyError(2*2)
exceptMyErroras e:
print('My exception occurred, value:', e.value)
My exception occurred, value:4
>>>raiseMyError('oops!')
Traceback(most recent call last):
File"<pyshell#64>", line 1,in<module>
raiseMyError('oops!')
MyError:'oops!'

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: