In Python, to handle errors and exceptions we use a try
-except
block.
The try
block contains the code where the exception might occur and the except
block contains the code that is executed when an exception occurs.
Here is the basic syntax:
main.py104 chars5 lines
For example:
main.py78 chars5 lines
In this example, we are trying to divide 5 by 0 which will raise a ZeroDivisionError. So, we’ve used a try
block to catch the error and print the message "Cannot divide by zero".
We can also catch more than one exception using multiple except
blocks:
main.py213 chars9 lines
Note that we can catch the base Exception class using the last except
block, which will handle all other exceptions. However, it is recommended to handle specific exceptions.
gistlibby LogSnag