Python Tutorial Python Advanced Python References Python Libraries

Python except Keyword



The Python except keyword is used in exception handling. Any error occurred in the try block of statement is handled by its except block of statement and the program will continue executing remaining part of code. Without try-except block, the program will stop immediately after an error and throw error message.

Syntax

try:
  statements
except:
  statements

Example:

In the example below, x is not defined anywhere in the program, which raises an error. As the error occurred in try block of statement, it will be handled by its except block of statement. Without try block, the program will stop immediately after an error and throw error message.

try:
  x = x + 1
  print(x)
except:
  print("An error occurred.")

print("But, it is handled by try-except blocks.")

The output of the above code will be:

An error occurred.
But, it is handled by try-except blocks.

Many except blocks

A program can have multiple except blocks to handle each type of exception differently.

Syntax

try:
  statements
except errortype_1:
  statements
except errortype_2:
  statements
...
...
except:
  statements

Example:

try:
  x = 1
  y = 0
  x = x / y 
  print(x)
except ZeroDivisionError:
  print("Zero Division Error")
except (ValueError, TypeError):
  print("Value/Type Error")
except:
  print("An error occurred.")

The output of the above code will be:

Zero Division Error

except block with else

else block statement can also be added with try-except blocks which is executed when no error has occurred.

Syntax

try:
  statements
except:
  statements
else:
  statements

Example:

try:
  x = 10
  y = 2
  x = x / y 
  print(x)
except ZeroDivisionError:
  print("Zero Division Error")
except:
  print("An error occurred.")
else:
  print("No error has occurred.")

The output of the above code will be:

5.0
No error has occurred.

❮ Python Keywords