0
Can any one explain me assert and raise in Python ?
It more confused me plse help me Friends
3 Réponses
+ 8
"assert" is used to assert that a certain condition is true. If it isn't, an AssertionError will be raised. You can add a string that is displayed together with the error message:
a = 25
assert 0 <= a <= 50, "Invalid value"
# output: (none, assertion is True)
a = 25
assert 0 <= a <= 20, "Invalid value"
# result: AssertionError: Invalid value
asserts should be used with care, because some interpreters have settings to simply ignore assert statements. In this case, even if the assert statement is False, nothing will happen. It's best to use them for debugging only.
"raise" raises a predefined or self-made exception:
a = 25
if a < 50:
raise ValueError("Invalid value")
# result: ValueError: Invalid value
It can also be used within a try/except block to raise the error after you inspected it:
try:
print(25/0)
except ZeroDivisionError:
print('can\'t divide by zero') # this catches the error
raise # this will raise the caught error
# result: This will output "can't divide by zero" first and then raise a ZeroDivisionError
+ 2
You can define your own exception like this:
class AgeError(Exception):
pass # empty class
raise AgeError('custom error message')
+ 1
Anna can you tell how we can raise our own error using class and raise plse
like raise AgeError