Holla Tech - Learn

Raising Exceptions
 

You can raise exceptions by using the raise statement. 

print(1)
raise ValueError
print(2

Result: 

>>
1
ValueError
>>> 

 

NOTE!
You need to specify the type of the exception raised.

Raising Exceptions
 

Exceptions can be raised with arguments that give detail about them.
For example:

name = “123”
raise NameError(“Invalid name!”

  

Result: 

>>
NameError: Invalid name!
>>> 

 


Raising Exceptions
 

In except blocks, the raise statement can be used without arguments to re-raise whatever exception occurred.
For example:

try:
   num = 5 / 0
except:
   print(“An error occurred”)
   raise 

 

Result: 

<

p dir=”ltr”>

>>>
An error occurred

ZeroDivisionError: division by zero
>>> 

 

NOTE!
You can try it yourself using a Python code editor. 

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE PYTHON MAIN COURSE PAGE. 

PYTHON MAIN COURSE PAGE

 


©️ License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT