Friday, 29 December 2023

python , django exception handling, raise custom exception

 https://docs.python.org/3/tutorial/errors.html

https://www.coursera.org/tutorials/python-exception


How to raise and catch

try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception type
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs


inst.args[0] will be 'spam'




Exception list:

ExceptionExplanationHierarchy
AttributeErrorWhen an attribute reference or assignment fails, this Python exception is raised.Inherits from Exception.
EOFErrorEOF stands for end-of-file. This exception is raised when an input() function reaches an EOF condition without reading any data.Inherits from Exception.
ImportErrorRaised when an import statement struggles to load a module. Can also be raised when a “from list” in from...import includes a name it cannot find.Inherits from Exception.
ModuleNotFoundErrorAlso raised by import. Occurs when a module cannot be located or when None is found in sys.modules.Inherits from Exception and is a subclass of ImportError.
ZeroDivisionErrorPython raises this type of error when the second argument of a modulo operation or a division is 0.Inherits from Exception and is a subclass of ArithmeticError.
IndexErrorThis exception occurs if a sequence subscript is out of range.Inherits from Exception.
KeyErrorRaised when a mapping key or, dictionary key, is not found in the existing set of keys.Inherits from Exception.
MemoryErrorRaised when there is not enough memory for the current operation. This exception can be addressed by deleting other objects.Inherits from Exception.
NameErrorWhen a global or local name cannot be found, this type of error is raised. The conditions for this exception only apply to unqualified names.Inherits from Exception.
ConnectionErrorBase class for issues related to connection.Inherits from Exception, belongs to the subclass of OS exceptions.
TypeErrorIf an operation or function is applied to an object of improper type, Python raises this exception.Inherits from Exception.
ValueErrorRaised when an operation or function receives the right type of argument but the wrong value and it cannot be matched by a more specific exception.I

No comments:

Post a Comment