try catch expept in python

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.py
try:
   # some code that may raise an exception
except ExceptionName:
   # code to handle the exception
104 chars
5 lines

For example:

main.py
try:
    x = 5/0
except ZeroDivisionError:
    print("Cannot divide by zero")
78 chars
5 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.py
try:
   # some code that may raise an exception
except ExceptionName1:
   # code to handle ExceptionName1
except ExceptionName2:
   # code to handle ExceptionName2
except:
   # code to handle all other exceptions
213 chars
9 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.

related categories

gistlibby LogSnag