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 statement handles these exceptions:

Example

The try block will generate an exception because x is undefined:

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

Run Instance

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

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

Example

This statement will raise an error because x is undefined:

print(x)

Run Instance

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:

Example

If the try block raises NameErrorPrint a message if it is another error:

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

Run Instance

Else

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

Example

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

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

Run Instance

Finally

If specified finally Whether the try block raises an error or not, the finally block will always be executed.

Example

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

Run Instance

This is very useful for closing objects and cleaning up resources:

Example

Attempt to open and write to an unwritable file:

try:
  f = open("demofile.txt")
  f.write("Lorum Ipsum")
except:
  print("Something went wrong when writing to the file")
finally:
  f.close()

Run Instance

The program can continue, and the file object will not be opened.

Raising Exceptions

As a Python developer, you can choose to raise an exception when a condition occurs.

To raise (trigger) an exception, use raise Keywords.

Example

If x is less than 0, an exception is raised and the program is terminated:

x = -1
if x < 0:
  raise Exception("Sorry, no numbers below zero")

Run Instance

raise Keywords are used to raise exceptions.

You can define the type of exception raised and the text printed to the user.

Example

If x is not an integer, a TypeError is raised:

x = "hello"
if not type(x) is int:
  raise TypeError("Only integers are allowed")

Run Instance