⊗pyPmExcDTC 76 of 128 menu

Catching Different Types of Exceptions in Python

In the same code, you may need to catch different types of exceptions.

Let's say we need to catch an exception when dividing by zero. This type of error results in an exception:

ZeroDivisionError: division by zero

To catch it, the exception name should be written in a except block:

try: print(1 / 0) except ZeroDivisionError: print('error: do not divide by zero')

Also let's say we have a list:

lst = [1, 2, 3]

If you specify code with another potential error in the try block, for example, with the output of a non-existent element, then the exception not caught in the except block will pass further and be output to the console. Because of which the code will stop working:

lst = [1, 2, 3] try: print(lst[4]) # IndexError: list index out of range except ZeroDivisionError: print('error: do not divide by zero')

To solve this situation, you need to specify the name of the corresponding exception type in each block. Let's add an exception for a missing element to our code:

try: print(lst[4]) except ZeroDivisionError: print('error: do not divide by zero') except IndexError: print('error: elem is not exist')

The following code is given:

txt = '2' res1 = txt + 3 res2 = txt1

Write code to catch the exceptions represented in the variables res1 and res2.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline