Python Try Except


Try block lets you check the code block for errors.

The except block lets you manage an error.

The block finally allows you to create code, regardless of the result of trying and without blocks.


Exception Handling

In the event of an error, or otherwise as we call it, Python will usually stop and produce an error message.

These exceptions can be addressed using the try statement:


Example

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

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

As the try block suggests an error, the except block will be used.

Without a try block, the system will crash and crash:


Example

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

print(x)


Many Exceptions

You can define as many different blocks as you want, e.g. if you want to create a special block code for a special type of error:


Example

Print one message if the try block raises a NameError and another for other errors:

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


Else

You can use else keyword to define a code block to use when no errors are suggested:


Example

In this example, the try block does not generate any error:

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


Finally

The finally block in the, if specified, will be used whether the try block suggests an error or not.


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

This can be useful for shutting down and cleaning utilities:


Example

Try to open and write to a file that is not writable:

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

The program can continue, without leaving the file object open.


Raise an exception

As a Python engineer you can choose a different throw in case.

To throw (or suggest) something different, use the raise keyword.


Example

Raise an error and stop the program if x is lower than 0:

x = -1

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

The keyword raise is used for a different suggestion.

You can specify what type of error should be raised, as well as the text to be printed on the user.


Example

Raise an error and stop the program if x is lower than 0:

x = "hello"

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