Python Raising Exceptions
Raising Exceptions in Python
The raise is a statement that allows the user to force a particular exception to occur. In order to throw an exception forcefully, raise keyword is used. We can raise an exception according to the fulfillment of the condition. This raise statement can be complemented with a custom exception.
Users can decide what type of error to raise and the text to print at the output. The exception object created be raise statement can contain a message that provides an error message. The raise statement creates an exception object, and leaves the expected program execution sequence to search the enclosing try statements for a matching except clause.
Raise statement either divert execution in a matching except suite, or stops the program if matching except suite was not found to handle the exception. There are two forms for the raise statements.
raise exceptionClass (, value)
This raise statement uses an exception class name, the optional parameter is the additional value which will be contained in the exception.
X= 6 if X%5!=0: raise ValueError(‘X should be multiple of 5’)
ValueError: X should be multiple of 5
x = 5.6 if not type(x) is int: raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed