How to raise exceptions in Python

A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception.
Sometimes you ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into. Instead of showing the message exception error
, Python details what type of exception error was encountered.
Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions. The later can be done using raise
.
We can use raise
to throw an exception if a particular condition occurs. The statement can be complemented with a custom exception.
If you want to throw an error when a certain condition occurs using raise
, given below is an example of raising an exception:
x = 5 if x < 10: raise Exception('x must be a two-digit number. The value of x was: {}'.format(x))
When you run this code, the output will be the following:
Traceback (most recent call last): File "C:\Users\user\Desktop\test.py", line 3, in <module> raise Exception('x must be a two-digit number. The value of x was: {}'.format(x)) Exception: x must be a two-digit number. The value of x was: 5
The program comes to a halt and displays our exception to screen, offering clues about what went wrong.
Raising an exception is completely user defined.