⊗pyPmExcFi 78 of 128 menu

The finally block when catching exceptions in Python

In situations where you need to print some message regardless of whether there are exceptions, you should use the finally block in the try-except construct.

Let's say we have a list and a try-except construct to catch a non-existent list element:

lst = [1, 2, 3] try: print(lst[4]) except IndexError: print('error: elem is not exist')

Let's refer to a non-existent list element, but in the finally block we will write the output of the sum of the elements:

lst = [1, 2, 3] try: print(lst[4]) except: print('error: elem is not exist') finally: print(sum(lst))

After executing the code, both the caught exception and the sum of the elements will be displayed:

'error: elem is not exist' 6

Given a string:

txt = 'abc'

Write code to catch the exception that occurs when adding 2 to a string. Also write a capital letter to the console to output the string.

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