The try except statement can handle exceptions. Exceptions may happen when y'all run a program.

Exceptions are errors that happen during execution of the plan. Python won't tell you lot well-nigh errors similar syntax errors (grammar faults), instead it will abruptly stop.

An abrupt get out is bad for both the end user and developer.

Instead of an emergency halt, you tin can use a attempt except argument to properly deal with the trouble. An emergency halt volition happen if yous do not properly handle exceptions.

Related grade: Complete Python Programming Course & Exercises

What are exceptions in Python?

Python has built-in exceptions which tin output an error. If an error occurs while running the program, information technology's called an exception.

If an exception occurs, the type of exception is shown. Exceptions needs to be dealt with or the program will crash. To handle exceptions, the try-catch cake is used.

Some exceptions you may have seen before are FileNotFoundError, ZeroDivisionError or ImportError but there are many more than.

All exceptions in Python inherit from the grade BaseException. If you open the Python interactive shell and type the following argument information technology will list all built-in exceptions:

The thought of the endeavor-except clause is to handle exceptions (errors at runtime). The syntax of the try-except block is:

                    1                    
2
3
4
                                          try:                    
<do something>
except Exception:
<handle the error>

The thought of the try-except cake is this:

  • effort: the code with the exception(southward) to take hold of. If an exception is raised, it jumps directly into the except block.

  • except: this code is only executed if an exception occured in the effort block. The except cake is required with a try block, even if information technology contains only the pass argument.

It may be combined with the else and finally keywords.

  • else: Lawmaking in the else block is but executed if no exceptions were raised in the effort block.

  • finally: The code in the finally cake is always executed, regardless of if a an exception was raised or non.

Catching Exceptions in Python

The attempt-except block tin handle exceptions. This prevents precipitous exits of the plan on mistake. In the instance below we purposely raise an exception.

                    one                    
two
three
4
v
6
                                          endeavour:                                        
one / 0
except ZeroDivisionError:
impress('Divided by zippo')

impress('Should achieve here')

After the except block, the program continues. Without a try-except block, the final line wouldn't be reached as the program would crash.

                                      $ python3 case.py

Divided by nothing
Should reach hither

In the above case we take hold of the specific exception ZeroDivisionError. You can handle any exception like this:

                    ane                    
two
iii
4
5
half-dozen
                                          endeavour:                                        
open up("fantasy.txt")
except:
impress('Something went wrong')

print('Should reach here')

You can write different logic for each blazon of exception that happens:

                    1                    
2
iii
4
5
6
7
viii
9
10
                                          try:                                        

except FileNotFoundError:

except IsADirectoryError:

except:


print('Should reach here')

Related form: Consummate Python Programming Class & Exercises

effort-except

Lets take practice a real world example of the try-except block.

The plan asks for numeric user input. Instead the user types characters in the input box. The program normally would crash. Simply with a try-except cake it can be handled properly.

The effort except statement prevents the program from crashing and properly deals with it.

                    1                    
2
three
4
5
6
                                          try:                    
x = input("Enter number: ")
x = 10 + ane
print(x)
except:
print("Invalid input")

Entering invalid input, makes the program continue normally:

try except

The endeavour except statement tin be extended with the finally keyword, this will exist executed if no exception is thrown:

                    one                    
2
                                          finally:                    
impress("Valid input.")

The program continues execution if no exception has been thrown.

In that location are unlike kinds of exceptions: ZeroDivisionError, NameError, TypeError and and then on. Sometimes modules define their own exceptions.

The try-except block works for office calls too:

                    1                    
two
three
4
5
half-dozen
vii
8
nine
                                                                  def                        fail                        ():                                        
one / 0

try:
neglect()
except:
print('Exception occured')

print('Program continues')

This outputs:

                                      $ python3 example.py

Exception occured
Programme continues

If you are a beginner, and so I highly recommend this book.

try finally

A try-except block can have the finally clause (optionally). The finally clause is always executed.
So the general idea is:

                    1                    
ii
3
4
five
six
                                          try:                    
<practise something>
except Exception:
<handle the mistake>
finally:
<cleanup>

For example: if you open a file you'll want to close information technology, you can exercise so in the finally clause.

                    one                    
ii
three
4
five
half-dozen
7
eight
                                          try:                                        
f = open("test.txt")
except:
print('Could non open file')
finally:
f.close()

print('Program continue')

try else

The else clause is executed if and merely if no exception is raised. This is different from the finally clause that'south ever executed.

                    one                    
ii
3
4
v
6
7
8
                                          effort:                    
x = 1
except:
print('Failed to set 10')
else:
print('No exception occured')
finally:
print('We always exercise this')

Output:

                                      No exception occured
Nosotros ever do this

You can catch many types of exceptions this way, where the else clause is executed only if no exception happens.

                    1                    
2
3
4
five
6
7
8
9
10
11
12
thirteen
xiv
                                          effort:                    
luncheon()
except SyntaxError:
impress('Fix your syntax')
except TypeError:
print('Oh no! A TypeError has occured')
except ValueError:
print('A ValueError occured!')
except ZeroDivisionError:
print('Did by zero?')
else:
print('No exception')
finally:
print('Ok and so')

Raise Exception

Exceptions are raised when an error occurs. But in Python yous tin can also force an exception to occur with the keyword raise.

Whatever type of exception can exist raised:

                    1                    
2
three
4
                                          >>>                                            raise                      MemoryError("Out of memory")                    
Traceback (most recent telephone call final):
File "<stdin>", line one, in <module>
MemoryError: Out of retentiveness
                    1                    
2
three
4
5
                                          >>>                                            raise                      ValueError("Wrong value")                    
Traceback (most recent phone call last):
File "<stdin>", line 1, in <module>
ValueError: Wrong value
>>>

Related grade: Consummate Python Programming Course & Exercises

Built-in exceptions

A list of Python'due south Born Exceptions is shown below. This list shows the Exception and why it is thrown (raised).
Exception Cause of Error
AssertionError if assert statement fails.
AttributeError if attribute assignment or reference fails.
EOFError if the input() functions hits stop-of-file condition.
FloatingPointError if a floating point operation fails.
GeneratorExit Raise if a generator's shut() method is chosen.
ImportError if the imported module is non found.
IndexError if alphabetize of a sequence is out of range.
KeyError if a central is non found in a dictionary.
KeyboardInterrupt if the user hits interrupt key (Ctrl+c or delete).
MemoryError if an operation runs out of memory.
NameError if a variable is not establish in local or global scope.
NotImplementedError by abstract methods.
OSError if system operation causes system related error.
OverflowError if result of an arithmetic operation is too large to be represented.
ReferenceError if a weak reference proxy is used to admission a garbage nerveless referent.
RuntimeError if an error does not fall under whatsoever other category.
StopIteration by adjacent() function to indicate that there is no farther item to be returned by iterator.
SyntaxError by parser if syntax error is encountered.
IndentationError if there is incorrect indentation.
TabError if indentation consists of inconsistent tabs and spaces.
SystemError if interpreter detects internal error.
SystemExit past sys.exit() function.
TypeError if a role or operation is applied to an object of incorrect type.
UnboundLocalError if a reference is made to a local variable in a role or method, but no value has been bound to that variable.
UnicodeError if a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError if a Unicode-related error occurs during encoding.
UnicodeDecodeError if a Unicode-related error occurs during decoding.
UnicodeTranslateError if a Unicode-related error occurs during translating.
ValueError if a part gets argument of right type but improper value.
ZeroDivisionError if second operand of division or modulo operation is zero.

User-divers Exceptions

Python has many standard types of exceptions, but they may not always serve your purpose.
Your program can have your own type of exceptions.

To create a user-defined exception, you have to create a grade that inherits from Exception.

                    ane                    
2
3
iv
                                                                  form                        LunchError                        (Exception):                                        
laissez passer

raise LunchError("Programmer went to lunch")

You fabricated a user-divers exception named LunchError in the higher up lawmaking. Y'all can raise this new exception if an error occurs.

Outputs your custom fault:

                                      $ python3 example.py
Traceback (most recent telephone call terminal):
File "instance.py", line 5, in
raise LunchError("Programmer went to luncheon")
principal.LunchError: Programmer went to luncheon

Your plan can have many user-defined exceptions. The program beneath throws exceptions based on a new projects money:

                    1                    
2
3
4
v
half dozen
vii
viii
nine
10
eleven
                                                                  course                        NoMoneyException                        (Exception):                                        
pass

grade OutOfBudget (Exception):
laissez passer

rest = int(input("Enter a balance: "))
if remainder < 1000:
raise NoMoneyException
elif balance > 10000:
raise OutOfBudget

Here are some sample runs:

                                      $ python3 example.py
Enter a remainder: 500
Traceback (well-nigh recent call final):
File "case.py", line 10, in
heighten NoMoneyException
main.NoMoneyException
                                      $ python3 instance.py
$ python3 example.py
Enter a balance: 100000
Traceback (near recent phone call final):
File "example.py", line 12, in
raise OutOfBudget
main.OutOfBudget

It is a good practice to put all user-defined exceptions in a separate file (exceptions.py or errors.py). This is common do in standard modules besides.

If you are a beginner, then I highly recommend this book.

Exercises

  1. Tin try-except exist used to catch invalid keyboard input?
  2. Tin effort-except grab the error if a file tin can't be opened?
  3. When would yous non use try-except?

Download examples