Home ProgrammingPythonPython Files & Exceptions Python Exceptions : How to handle failures

Python Exceptions : How to handle failures

by WhereWhatHow
Python Exceptions

Python exceptions : unexpected event that occurs during program execution. For example,

divide_by_zero = 7 / 0

The above code causes an exception as it is not possible to divide a number by 0.

Let’s learn about Python Exceptions in detail.

Python Exceptions : Logical Errors

Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors.

For instance, they occur when we

  • open a file(for reading) that does not exist (FileNotFoundError)
  • divide a number by zero (ZeroDivisionError)
  • import a module that does not exist (ImportError) and so on.

Whenever these types of runtime errors occur, Python creates an exception object.

If not handled properly, it prints a traceback to that error along with some details about why that error occurred.

Let’s look at how Python treats these errors:

divide_numbers = 7 / 0
prit(divide_numbers)

Output

Traceback (most recent call last):
 File "<string>", line 1, in <module>
ZeroDivisionError: division by zero

Here, while trying to divide 7 / 0, the program throws a system exception ZeroDivisionError

Python Built-in Exceptions

Illegal operations can raise exceptions. In Python, there are plenty of built-in exceptions thrown when corresponding errors occur.

We can view all the built-in exceptions using the built-in local() function as follows:

print(dir(locals()['__builtins__']))

Here, locals()['__builtins__'] will return a module of built-in exceptions, functions, and attributes and dir allows us to list these attributes as strings.

Some of the common built-in exceptions in Python programming along with the error that cause them:

ExceptionCause of Error
AssertionErrorRaised when an assert statement fails.
AttributeErrorRaised when attribute assignment or reference fails.
EOFErrorRaised when the input() function hits end-of-file condition.
FloatingPointErrorRaised when a floating point operation fails.
GeneratorExitRaise when a generator’s close() method is called.
ImportErrorRaised when the imported module is not found.
IndexErrorRaised when the index of a sequence is out of range.
KeyErrorRaised when a key is not found in a dictionary.
KeyboardInterruptRaised when the user hits the interrupt key (Ctrl+C or Delete).
MemoryErrorRaised when an operation runs out of memory.
NameErrorRaised when a variable is not found in local or global scope.
NotImplementedErrorRaised by abstract methods.
OSErrorRaised when system operation causes system related error.
OverflowErrorRaised when the result of an arithmetic operation is too large to be represented.
ReferenceErrorRaised when a weak reference proxy is used to access a garbage collected referent.
RuntimeErrorRaised when an error does not fall under any other category.
StopIterationRaised by next() function to indicate that there is no further item to be returned by iterator.
SyntaxErrorRaised by parser when syntax error is encountered.
IndentationErrorRaised when there is incorrect indentation.
TabErrorRaised when indentation consists of inconsistent tabs and spaces.
SystemErrorRaised when interpreter detects internal error.
SystemExitRaised by sys.exit() function.
TypeErrorRaised when a function or operation is applied to an object of incorrect type.
UnboundLocalErrorRaised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeErrorRaised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeErrorRaised when a Unicode-related error occurs during encoding.
UnicodeDecodeErrorRaised when a Unicode-related error occurs during decoding.
UnicodeTranslateErrorRaised when a Unicode-related error occurs during translating.
ValueErrorRaised when a function gets an argument of correct type but improper value.
ZeroDivisionErrorRaised when the second operand of division or modulo operation is zero.

If required, we can also define our own exceptions in Python. To learn more about them, visit Python User-defined Exceptions.

We can handle these built-in and user-defined exceptions in Python using tryexcept and finally statements. To learn more about them, visit Python try, except and finally statements.

Python Error and Exception

Errors represent conditions such as compilation error, syntax error, error in the logical part of the code, library incompatibility, infinite recursion, etc.

Errors are usually beyond the control of the programmer and we should not try to handle errors.

Exceptions can be caught and handled by the program.

Now we know about exceptions, we will learn about handling exceptions in the next tutorial.

Python Exceptions

Related Posts

Leave a Comment