Python Try Except

try block allows you to test code blocks to find errors.

except block allows you to handle errors.

finally block allows you to execute code regardless of the result of the try and except blocks.

Exception handling

When we call Python and an error or exception occurs, we usually stop and generate an error message.

You can use try statements to handle these exceptions:

Esimerkki

The try block will generate an exception because x is not defined:

try:
  print(x)
except:
  print("An exception occurred")

Suorita Esimerkki

Since the try block raised an error, the except block will be executed.

If there is no try block, the program will crash and an error will be raised:

Esimerkki

This statement will raise an error because x is not defined:

print(x)

Suorita Esimerkki

Multiple exceptions

You can define any number of exception blocks as needed, for example, if you want to execute special code blocks for special types of errors:

Esimerkki

If the try block raises NameErrorThen print a message, or print another message for other errors:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

Suorita Esimerkki

Else

If no error is raised, you can use else keywords to define the code block to be executed:

Esimerkki

In this example,try The block will not generate any errors:

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

Suorita Esimerkki

Finally

If specified finally If a block is used, the finally block will be executed regardless of whether an error is raised in the try block.

Esimerkki

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

Suorita Esimerkki

Tämä on hyödyllistä sulkea objekteja ja puhdistaa resursseja:

Esimerkki

Yritä avata ja kirjoittaa kirjoittamattomaan tiedostoon:

try:
  f = open("demofile.txt")
  f.write("Lorum Ipsum")
except:
  print("Tiedoston kirjoittamisen aikana tapahtui virhe")
finally:
  f.close()

Suorita Esimerkki

Ohjelma voi jatkaa sujuvasti eikä avaa tiedostojoukkoa.

Aiheuta poikkeus

Python-kehittäjänä voit valita heittää poikkeuksen, kun ehdot täyttyvät.

Jos haluat heittää (aiheuttaa) poikkeuksen, käytä raise Avainsanat.

Esimerkki

Jos x on alle nollan, niin aiheutetaan poikkeus ja ohjelma lopetetaan:

x = -1
if x < 0:
  raise Exception("Pahoittelut, ei lukuja alle nollan")

Suorita Esimerkki

raise Avainsanat aiheuttavat poikkeuksia.

Voit määritellä aiheutetun poikkeuksen tyyppin ja tulostaa tekstiä käyttäjälle.

Esimerkki

Jos x ei ole kokonaisluku, niin aiheutetaan TypeError:

x = "hello"
if not type(x) is int:
  raise TypeError("Vain kokonaisluvut sallittu")

Suorita Esimerkki