Exception Handling in Python

Garrett Keyes
Nov 6 · 4 min read

Using Python try and except clauses can save programmers time and headaches.

Nothing is more frustrating than writing a beautiful function only to have a bug in the code return an error. But using try and except clauses, Python programmers can avoid those situations, or at least handle them better, DataCamp suggests.

Source: GIFY

Try an except clauses are used to tell python to try running something we expect to work, but if an error is produced do whatever is specified within the except clause. To use try and except clauses in python you must include the try and except clauses within the desired block of code, as you would for an if/else statements. Python will then check if the code indented within the first try clause will run without error and if an exception occurs it will proceed to the exception clause.

In this example, x was never defined so it produces an error when the function is run.

Exceptions can also be used to look for specific types of errors instead of using a broad except to catch all errors.

In this instance the exception clause was set to catch all exceptions that contain a ValueError, which happens when a function gets an argument of proper type but improper value. In this instance that means passing a string into an int method.

Except clauses can also be linked by separating each clause with a comma. This says what python will do if any of the specified exceptions appear from the listed values.

To complete the process of exception handling the finally clause can be coupled with the try and except clauses. The finally cause works in the case where there is code you want to be executed regardless of whether an exception occurs or not. When exceptions happen, python jumps ahead to the finally block to execute all the lines of code in the block. It then jumps back to the except block to handle the exception.

But to understand the try and except clauses it’s essential to understand how to handle errors as they appear in Python. Errors can fall within two main categories — syntax errors and runtime errors, otherwise known as exception errors. Syntax errors, which are also called parsing errors, are the most common type of error and occur when the parser is unable to interpret the python code, documentation shows. They most commonly occur from simply spelling or spacing issues. Runtime errors occur when python understands what you are saying, but runs into problems when following your directions.

Runtime error types include:

  • ArithmeticError — When numeric calculations fail.
  • FloatingPointError — When a floating point calculation fails.
  • ZeroDivisionError — Raised when division or modulo by zero takes place for all numeric types.
  • AssertionError — Arises when an assert statement fails.
  • OverflowError — When the result of an arithmetic operation is too large to be represented.
  • ImportError — Appears when the imported module cannot be found.
  • IndexError — Appears when the index of a sequence is out of range.
  • KeyboardInterrupt — Shows up when the user interrupts program execution, which is usually done by pressing Ctrl+c.
  • IndentationError — Appears when there is incorrect indentation.
  • KeyError — Appear when the specified key is not found in the dictionary.
  • NameError — Appears when an identifier can’t be found in the local or global namespace.
  • TypeError — Shows up when a function or operation is applied to an object of incorrect type.
  • ValueError — Appears when a function gets an argument of correct type but improper value.
  • IOError — Raised when an input/ output operation fails.
  • RuntimeError — This is the error of last option. It is raised when a generated error does not fall into any other category.
Source: Tenor

Including too many try and except clauses can be problematic however, DataCamp says. Besides increasing the potential of getting lost in additional code, python files that use try and except often run slower. So be careful to only use them strictly in exceptional circumstances and don’t cross the line with their frequency.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade