Python exception error types

In this beginner tutorial you'll learn what exceptions are good for in Python. You'll see how to raise exceptions and how to handle them with "try/except" blocks.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions

A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception. In this article, you will see what an exception is and how it differs from a syntax error. After that, you will learn about raising exceptions and making assertions. Then, you’ll finish with a demonstration of the try and except block.

An introduction to exceptions in Python

Exceptions versus Syntax Errors

Syntax errors occur when the parser detects an incorrect statement. Observe the following example:

>>> print( 0 / 0 ))
  File "<stdin>", line 1
    print( 0 / 0 ))
                  ^
SyntaxError: invalid syntax

The arrow indicates where the parser ran into the syntax error. In this example, there was one bracket too many. Remove it and run your code again:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into.

Instead of showing the message exception error, Python details what type of exception error was encountered. In this case, it was a ZeroDivisionError. Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions.

Raising an Exception

We can use raise to throw an exception if a condition occurs. The statement can be complemented with a custom exception.

Illustration of  raise statement usage

If you want to throw an error when a certain condition occurs using raise, you could go about it like this:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))

When you run this code, the output will be the following:

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10

The program comes to a halt and displays our exception to screen, offering clues about what went wrong.

The AssertionError Exception

Instead of waiting for a program to crash midway, you can also start by making an assertion in Python. We assert that a certain condition is met. If this condition turns out to be True, then that is excellent! The program can continue. If the condition turns out to be False, you can have the program throw an AssertionError exception.

Python assert statement

Have a look at the following example, where it is asserted that the code will be executed on a Linux system:

import sys
assert ('linux' in sys.platform), "This code runs on Linux only."

If you run this code on a Linux machine, the assertion passes. If you were to run this code on a Windows machine, the outcome of the assertion would be False and the result would be the following:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.

In this example, throwing an AssertionError exception is the last thing that the program will do. The program will come to halt and will not continue. What if that is not what you want?

The try and except Block: Handling Exceptions

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding try clause.

Diagram showing try and except statements

As you saw earlier, when syntactically correct code runs into an error, Python will throw an exception error. This exception error will crash the program if it is unhandled. The except clause determines how your program responds to exceptions.

The following function can help you understand the try and except block:

def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')

The linux_interaction() can only run on a Linux system. The assert in this function will throw an AssertionError exception if you call it on an operating system other then Linux.

You can give the function a try using the following code:

try:
    linux_interaction()
except:
    pass

The way you handled the error here is by handing out a pass. If you were to run this code on a Windows machine, you would get the following output:

You got nothing. The good thing here is that the program did not crash. But it would be nice to see if some type of exception occurred whenever you ran your code. To this end, you can change the pass into something that would generate an informative message, like so:

try:
    linux_interaction()
except:
    print('Linux function was not executed')

Execute this code on a Windows machine:

Linux function was not executed

When an exception occurs in a program running this function, the program will continue as well as inform you about the fact that the function call was not successful.

What you did not get to see was the type of error that was thrown as a result of the function call. In order to see exactly what went wrong, you would need to catch the error that the function threw.

The following code is an example where you capture the AssertionError and output that message to screen:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
    print('The linux_interaction() function was not executed')

Running this function on a Windows machine outputs the following:

Function can only run on Linux systems.
The linux_interaction() function was not executed

The first message is the AssertionError, informing you that the function can only be executed on a Linux machine. The second message tells you which function was not executed.

In the previous example, you called a function that you wrote yourself. When you executed the function, you caught the AssertionError exception and printed it to screen.

Here’s another example where you open a file and use a built-in exception:

try:
    with open('file.log') as file:
        read_data = file.read()
except:
    print('Could not open file.log')

If file.log does not exist, this block of code will output the following:

This is an informative message, and our program will still continue to run. In the Python docs, you can see that there are a lot of built-in exceptions that you can use here. One exception described on that page is the following:

Exception FileNotFoundError

Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.

To catch this type of exception and print it to screen, you could use the following code:

try:
    with open('file.log') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)

In this case, if file.log does not exist, the output will be the following:

[Errno 2] No such file or directory: 'file.log'

You can have more than one function call in your try clause and anticipate catching various exceptions. A thing to note here is that the code in the try clause will stop as soon as an exception is encountered.

Look at the following code. Here, you first call the linux_interaction() function and then try to open a file:

try:
    linux_interaction()
    with open('file.log') as file:
        read_data = file.read()
except FileNotFoundError as fnf_error:
    print(fnf_error)
except AssertionError as error:
    print(error)
    print('Linux linux_interaction() function was not executed')

If the file does not exist, running this code on a Windows machine will output the following:

Function can only run on Linux systems.
Linux linux_interaction() function was not executed

Inside the try clause, you ran into an exception immediately and did not get to the part where you attempt to open file.log. Now look at what happens when you run the code on a Linux machine:

[Errno 2] No such file or directory: 'file.log'

Here are the key takeaways:

  • A try clause is executed up until the point where the first exception is encountered.
  • Inside the except clause, or the exception handler, you determine how the program responds to the exception.
  • You can anticipate multiple exceptions and differentiate how the program should respond to them.
  • Avoid using bare except clauses.

The else Clause

In Python, using the else statement, you can instruct a program to execute a certain block of code only in the absence of exceptions.

Diagram of try, except, and else statements in Python

Look at the following example:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    print('Executing the else clause.')

If you were to run this code on a Linux system, the output would be the following:

Doing something.
Executing the else clause.

Because the program did not run into any exceptions, the else clause was executed.

You can also try to run code inside the else clause and catch possible exceptions there as well:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)

If you were to execute this code on a Linux machine, you would get the following result:

Doing something.
[Errno 2] No such file or directory: 'file.log'

From the output, you can see that the linux_interaction() function ran. Because no exceptions were encountered, an attempt to open file.log was made. That file did not exist, and instead of opening the file, you caught the FileNotFoundError exception.

Cleaning Up After Using finally

Imagine that you always had to implement some sort of action to clean up after executing your code. Python enables you to do so using the finally clause.

Diagram explaining try except else finally statements

Have a look at the following example:

try:
    linux_interaction()
except AssertionError as error:
    print(error)
else:
    try:
        with open('file.log') as file:
            read_data = file.read()
    except FileNotFoundError as fnf_error:
        print(fnf_error)
finally:
    print('Cleaning up, irrespective of any exceptions.')

In the previous code, everything in the finally clause will be executed. It does not matter if you encounter an exception somewhere in the try or else clauses. Running the previous code on a Windows machine would output the following:

Function can only run on Linux systems.
Cleaning up, irrespective of any exceptions.

Summing Up

After seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. In this article, you saw the following options:

  • raise allows you to throw an exception at any time.
  • assert enables you to verify if a certain condition is met and throw an exception if it isn’t.
  • In the try clause, all statements are executed until an exception is encountered.
  • except is used to catch and handle the exception(s) that are encountered in the try clause.
  • else lets you code sections that should run only when no exceptions are encountered in the try clause.
  • finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.

Hopefully, this article helped you understand the basic tools that Python has to offer when dealing with exceptions.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions

Nov 1, 2017 10:10:27 PM |
The Python Exception Class Hierarchy

An overview of the Python exception class hierarchy, including a quick look at all the top-level exception classes in the standard library.

The Python exception class hierarchy consists of a few dozen different exceptions spread across a handful of important base class types. As with most programming languages, errors occur within a Python application when something unexpected goes wrong. Anything from improper arithmetic and running out of memory to invalid file references and unicode formatting errors may be raised by Python under certain circumstances.

Most of the errors we’ll explore in this series are considered exceptions, which indicate that these are non-fatal errors. While a fatal error will halt execution of the current application, all non-fatal exceptions allow execution to continue. This allows our code to explicitly catch or rescue the raised exception and programmatically react to it in an appropriate manner.

Let’s start by looking at the full Python exception class hierarchy, as seen below:

  • BaseException
    • Exception
      • ArithmeticError
        • FloatingPointError
        • OverflowError
        • ZeroDivisionError
      • AssertionError
      • AttributeError
      • BufferError
      • EOFError
      • ImportError
        • ModuleNotFoundError
      • LookupError
        • IndexError
        • KeyError
      • MemoryError
      • NameError
        • UnboundLocalError
      • OSError
        • BlockingIOError
        • ChildProcessError
        • ConnectionError
          • BrokenPipeError
          • ConnectionAbortedError
          • ConnectionRefusedError
          • ConnectionResetError
        • FileExistsError
        • FileNotFoundError
        • InterruptedError
        • IsADirectoryError
        • NotADirectoryError
        • PermissionError
        • ProcessLookupError
        • TimeoutError
      • ReferenceError
      • RuntimeError
        • NotImplementedError
        • RecursionError
      • StopIteration
      • StopAsyncIteration
      • SyntaxError
        • IndentationError
          • TabError
      • SystemError
      • TypeError
      • ValueError
        • UnicodeError
          • UnicodeDecodeError
          • UnicodeEncodeError
          • UnicodeTranslateError
      • Warning
        • BytesWarning
        • DeprecationWarning
        • FutureWarning
        • ImportWarning
        • PendingDeprecationWarning
        • ResourceWarning
        • RuntimeWarning
        • SyntaxWarning
        • UnicodeWarning
        • UserWarning
    • GeneratorExit
    • KeyboardInterrupt
    • SystemExit

As we publish future exception-specific articles in this series we’ll update the full list above to relevant tutorial and article links for each exception, so this post can act as a go-to resource for Python exception handling tips.

Major Exception Types Overview

Next, let’s briefly discuss each important top-level exception type. These top-level exceptions will serve as a basis for digging into specific exceptions in future articles. Before we do that, however, it’s worth pointing out what might appear as a slight discrepancy when looking over the list of exception classes provided in Python. To illustrate, look closely at this small snippet of the Python exception class hierarchy and see if anything slightly strange pops out to you:

  • BaseException
    • Exception
      • ArithmeticError
        • FloatingPointError
        • OverflowError
        • ZeroDivisionError
      • AssertionError

For developers that have worked with other programming languages in the past, what you might take note of is the distinction between using the word exception in the BaseException and Exception parent classes, and the use of error in most subclasses therein. Most other languages, such as .NET or Java, explicitly differentiate between exceptions and errors by separating them into distinct categories. In such languages, errors typically denote fatal errors (those that crash the application), whereas exceptions are catchable/rescuable errors.

Yet, as we see in the hierarchy above, Python merely inherits from Exception with a series of XYZError classes. The reason for this naming convention comes from the PEP8 Python style guide, which makes an explicit mention that «you should use the suffix ‘Error’ on your exception names (if the exception is actually an error).» I’ve added the extra emphasis to that quote, because the latter point is critical here — most Python exceptions with Error in the name are, in fact, errors.

BaseException

The BaseException class is, as the name suggests, the base class for all built-in exceptions in Python. Typically, this exception is never raised on its own, and should instead be inherited by other, lesser exception classes that can be raised.

The BaseException class (and, thus, all subclass exceptions as well) allows a tuple of arguments to be passed when creating a new instance of the class. In most cases, a single argument will be passed to an exception, which is a string value indicating the specific error message.

This class also includes a with_traceback(tb) method, which explicitly sets the new traceback information to the tb argument that was passed to it.

Exception

Exception is the most commonly-inherited exception type (outside of the true base class of BaseException). In addition, all exception classes that are considered errors are subclasses of the Exception class. In general, any custom exception class you create in your own code should inherit from Exception.

The Exception class contains many direct child subclasses that handle most Python errors, so we’ll briefly go over each below:

  • ArithmeticError — The base class for the variety of arithmetic errors, such as when attempting to divide by zero, or when an arithmetic result would be too large for Python to accurately represent.
  • AssertionError — This error is raised when a call to the [assert] statement fails.
  • AttributeError — Python’s syntax includes something called attribute references, which is just the Python way of describing what you might know of as dot notation. In essence, any primary token in Python (like an identifier, literal, and so forth) can be written and followed by a period (.), which is then followed by an identifier. That syntax (i.e. primary.identifier) is called an attribute reference, and anytime the executing script encounters an error in such syntax an AttributeError is raised.
  • BufferError — Python allows applications to access low level memory streams in the form of a buffer. For example, the bytes class can be used to directly work with bytes of information via a memory buffer. When something goes wrong within such a buffer operation a BufferError is raised.
  • EOFError — Similar to the Java EOFException article we did a few days ago, Python’s EOFError is raised when using the input() function and reaching the end of a file without any data.
  • ImportError — Modules are usually loaded in memory for Python scripts to use via the import statement (e.g. import car from vehicles). However, if an import attempt fails an ImportError will often be raised.
  • LookupError — Like ArithmeticError, the LookupError is generally considered a base class from which other subclasses should inherit. All LookupError subclasses deal with improper calls to a collection are made by using invalid key or index values.
  • MemoryError — In the event that your Python application is about to run out of memory a MemoryError will be raised. Since Python is smart enough to detect this potential issue slightly before all memory is used up, a MemoryError can be rescued and allow you to recover from the situation by performing garbage collection of some kind.
  • NameError — Raised when trying to use an identifier with an invalid or unknown name.
  • OSError — This error is raised when a system-level problem occurs, such as failing to find a local file on disk or running out of disk space entirely. OSError is a parent class to many subclasses explicitly used for certain issues related to operating system failure, so we’ll explore those in future publications.
  • ReferenceError — Python includes the weakref module, which allows Python code to create a specific type of reference known as a weak reference. A weak reference is a reference that is not «strong» enough to keep the referenced object alive. This means that the next cycle of garbage collection will identify the weakly referenced object as no longer strongly referenced by another object, causing the weakly referenced object to be destroyed to free up resources. If a weak reference proxy created via the weakref.proxy() function is used after the object that is referenced has already been destroyed via garbage collection, a ReferenceError will be raised.
  • RuntimeError — A RuntimeError is typically used as a catchall for when an error occurs that doesn’t really fit into any other specific error classification.
  • StopIteration — If no default value is passed to the next() function when iterating over a collection, and that collection has no more iterated value to retrieve, a StopIteration exception is raised. Note that this is not classified as an Error, since it doesn’t mean that an error has occurred.
  • StopAsyncIteration — As of version 3.5, Python now includes coroutines for asynchronous transactions using the async and await syntax. As part of this feature, collections can be asynchronously iterated using the __anext__() method. The __anext__() method requires that a StopAsyncIteration instance be raised in order to halt async iteration.
  • SyntaxError — Just like most programming languages, a SyntaxError in Python indicates that there is some improper syntax somewhere in your script file. A SyntaxError can be raised directly from an executing script, or produced via functions like eval() and exec().
  • SystemError — A generic error that is raised when something goes wrong with the Python interpreter (not to be confused with the OSError, which handles operating system issues).
  • TypeError — This error is raised when attempting to perform an operation on an incorrect object type.
  • ValueError — Should be raised when a function or method receives an argument of the correct type, but with an actual value that is invalid for some reason.
  • Warning — Another parent class to many subclasses, the Warning class is used to alert the user in non-dire situations. There are a number of subclass warnings that we’ll explore in future articles.

GeneratorExit

A generator is a specific type of iterator in Python, which simplifies the process of creating iterators with constantly changing values. By using the yield statement within a generator code block, Python will return or «generate» a new value for each call to next(). When the explicit generator.close() method is called a GeneratorExit instance is raised.

KeyboardInterrupt

This simple exception is raised when the user presses a key combination that causes an interrupt to the executing script. For example, many terminals accept Ctrl+C as an interrupt keystroke.

SystemExit

Finally, the SystemExit exception is raised when calling the sys.exit() method, which explicitly closes down the executing script and exits Python. Since this is an exception, it can be rescued and programmatically responded to immediately before the script actually shuts down.


That’s just a small taste of the powerful, built-in Python exception class hierarchy as of version 3.6. Stay tuned for more in-depth articles examining each of these exceptions in greater detail, and be sure to check out Airbrake’s robust error monitoring software, which provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake’s state of the art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. No matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize exception parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.

Check out Airbrake’s error monitoring software today with a 14-day trial and see for yourself why so many of the world’s best engineering teams use Airbrake to revolutionize their exception handling practices!

In Python, all exceptions must be instances of a class that derives from
BaseException. In a try statement with an except
clause that mentions a particular class, that clause also handles any exception
classes derived from that class (but not exception classes from which it is
derived). Two exception classes that are not related via subclassing are never
equivalent, even if they have the same name.

The built-in exceptions listed below can be generated by the interpreter or
built-in functions. Except where mentioned, they have an “associated value”
indicating the detailed cause of the error. This may be a string or a tuple of
several items of information (e.g., an error code and a string explaining the
code). The associated value is usually passed as arguments to the exception
class’s constructor.

User code can raise built-in exceptions. This can be used to test an exception
handler or to report an error condition “just like” the situation in which the
interpreter raises the same exception; but beware that there is nothing to
prevent user code from raising an inappropriate error.

The built-in exception classes can be subclassed to define new exceptions;
programmers are encouraged to derive new exceptions from the Exception
class or one of its subclasses, and not from BaseException. More
information on defining exceptions is available in the Python Tutorial under
User-defined Exceptions.

When raising (or re-raising) an exception in an except or
finally clause
__context__ is automatically set to the last exception caught; if the
new exception is not handled the traceback that is eventually displayed will
include the originating exception(s) and the final exception.

When raising a new exception (rather than using a bare raise to re-raise
the exception currently being handled), the implicit exception context can be
supplemented with an explicit cause by using from with
raise:

raise new_exc from original_exc

The expression following from must be an exception or None. It
will be set as __cause__ on the raised exception. Setting
__cause__ also implicitly sets the __suppress_context__
attribute to True, so that using raise new_exc from None
effectively replaces the old exception with the new one for display
purposes (e.g. converting KeyError to AttributeError, while
leaving the old exception available in __context__ for introspection
when debugging.

The default traceback display code shows these chained exceptions in
addition to the traceback for the exception itself. An explicitly chained
exception in __cause__ is always shown when present. An implicitly
chained exception in __context__ is shown only if __cause__
is None and __suppress_context__ is false.

In either case, the exception itself is always shown after any chained
exceptions so that the final line of the traceback always shows the last
exception that was raised.

5.1. Base classes¶

The following exceptions are used mostly as base classes for other exceptions.

exception BaseException

The base class for all built-in exceptions. It is not meant to be directly
inherited by user-defined classes (for that, use Exception). If
str() is called on an instance of this class, the representation of
the argument(s) to the instance are returned, or the empty string when
there were no arguments.

args

The tuple of arguments given to the exception constructor. Some built-in
exceptions (like OSError) expect a certain number of arguments and
assign a special meaning to the elements of this tuple, while others are
usually called only with a single string giving an error message.

with_traceback(tb)

This method sets tb as the new traceback for the exception and returns
the exception object. It is usually used in exception handling code like
this:

try:
    ...
except SomeException:
    tb = sys.exc_info()[2]
    raise OtherException(...).with_traceback(tb)
exception Exception

All built-in, non-system-exiting exceptions are derived from this class. All
user-defined exceptions should also be derived from this class.

exception ArithmeticError

The base class for those built-in exceptions that are raised for various
arithmetic errors: OverflowError, ZeroDivisionError,
FloatingPointError.

exception BufferError

Raised when a buffer related operation cannot be
performed.

exception LookupError

The base class for the exceptions that are raised when a key or index used on
a mapping or sequence is invalid: IndexError, KeyError. This
can be raised directly by codecs.lookup().

5.2. Concrete exceptions¶

The following exceptions are the exceptions that are usually raised.

exception AssertionError

Raised when an assert statement fails.

exception AttributeError

Raised when an attribute reference (see Attribute references) or
assignment fails. (When an object does not support attribute references or
attribute assignments at all, TypeError is raised.)

exception EOFError

Raised when the input() function hits an end-of-file condition (EOF)
without reading any data. (N.B.: the io.IOBase.read() and
io.IOBase.readline() methods return an empty string when they hit EOF.)

exception FloatingPointError

Raised when a floating point operation fails. This exception is always defined,
but can only be raised when Python is configured with the
--with-fpectl option, or the WANT_SIGFPE_HANDLER symbol is
defined in the pyconfig.h file.

exception GeneratorExit

Raised when a generator or coroutine is closed;
see generator.close() and coroutine.close(). It
directly inherits from BaseException instead of Exception since
it is technically not an error.

exception ImportError

Raised when the import statement has troubles trying to
load a module. Also raised when the “from list” in from ... import
has a name that cannot be found.

The name and path attributes can be set using keyword-only
arguments to the constructor. When set they represent the name of the module
that was attempted to be imported and the path to any file which triggered
the exception, respectively.

Changed in version 3.3: Added the name and path attributes.

exception ModuleNotFoundError

A subclass of ImportError which is raised by import
when a module could not be located. It is also raised when None
is found in sys.modules.

New in version 3.6.

exception IndexError

Raised when a sequence subscript is out of range. (Slice indices are
silently truncated to fall in the allowed range; if an index is not an
integer, TypeError is raised.)

exception KeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

exception KeyboardInterrupt

Raised when the user hits the interrupt key (normally Control-C or
Delete). During execution, a check for interrupts is made
regularly. The exception inherits from BaseException so as to not be
accidentally caught by code that catches Exception and thus prevent
the interpreter from exiting.

exception MemoryError

Raised when an operation runs out of memory but the situation may still be
rescued (by deleting some objects). The associated value is a string indicating
what kind of (internal) operation ran out of memory. Note that because of the
underlying memory management architecture (C’s malloc() function), the
interpreter may not always be able to completely recover from this situation; it
nevertheless raises an exception so that a stack traceback can be printed, in
case a run-away program was the cause.

exception NameError

Raised when a local or global name is not found. This applies only to
unqualified names. The associated value is an error message that includes the
name that could not be found.

exception NotImplementedError

This exception is derived from RuntimeError. In user defined base
classes, abstract methods should raise this exception when they require
derived classes to override the method, or while the class is being
developed to indicate that the real implementation still needs to be added.

Note

It should not be used to indicate that an operator or method is not
meant to be supported at all – in that case either leave the operator /
method undefined or, if a subclass, set it to None.

Note

NotImplementedError and NotImplemented are not interchangeable,
even though they have similar names and purposes. See
NotImplemented for details on when to use it.

exception OSError([arg])
exception OSError(errno, strerror[, filename[, winerror[, filename2]]])

This exception is raised when a system function returns a system-related
error, including I/O failures such as “file not found” or “disk full”
(not for illegal argument types or other incidental errors).

The second form of the constructor sets the corresponding attributes,
described below. The attributes default to None if not
specified. For backwards compatibility, if three arguments are passed,
the args attribute contains only a 2-tuple
of the first two constructor arguments.

The constructor often actually returns a subclass of OSError, as
described in OS exceptions below. The particular subclass depends on
the final errno value. This behaviour only occurs when
constructing OSError directly or via an alias, and is not
inherited when subclassing.

errno

A numeric error code from the C variable errno.

winerror

Under Windows, this gives you the native
Windows error code. The errno attribute is then an approximate
translation, in POSIX terms, of that native error code.

Under Windows, if the winerror constructor argument is an integer,
the errno attribute is determined from the Windows error code,
and the errno argument is ignored. On other platforms, the
winerror argument is ignored, and the winerror attribute
does not exist.

strerror

The corresponding error message, as provided by
the operating system. It is formatted by the C
functions perror() under POSIX, and FormatMessage()
under Windows.

filename
filename2

For exceptions that involve a file system path (such as open() or
os.unlink()), filename is the file name passed to the function.
For functions that involve two file system paths (such as
os.rename()), filename2 corresponds to the second
file name passed to the function.

Changed in version 3.3: EnvironmentError, IOError, WindowsError,
socket.error, select.error and
mmap.error have been merged into OSError, and the
constructor may return a subclass.

Changed in version 3.4: The filename attribute is now the original file name passed to
the function, instead of the name encoded to or decoded from the
filesystem encoding. Also, the filename2 constructor argument and
attribute was added.

exception OverflowError

Raised when the result of an arithmetic operation is too large to be
represented. This cannot occur for integers (which would rather raise
MemoryError than give up). However, for historical reasons,
OverflowError is sometimes raised for integers that are outside a required
range. Because of the lack of standardization of floating point exception
handling in C, most floating point operations are not checked.

exception RecursionError

This exception is derived from RuntimeError. It is raised when the
interpreter detects that the maximum recursion depth (see
sys.getrecursionlimit()) is exceeded.

New in version 3.5: Previously, a plain RuntimeError was raised.

exception ReferenceError

This exception is raised when a weak reference proxy, created by the
weakref.proxy() function, is used to access an attribute of the referent
after it has been garbage collected. For more information on weak references,
see the weakref module.

exception RuntimeError

Raised when an error is detected that doesn’t fall in any of the other
categories. The associated value is a string indicating what precisely went
wrong.

exception StopIteration

Raised by built-in function next() and an iterator‘s
__next__() method to signal that there are no further
items produced by the iterator.

The exception object has a single attribute value, which is
given as an argument when constructing the exception, and defaults
to None.

When a generator or coroutine function
returns, a new StopIteration instance is
raised, and the value returned by the function is used as the
value parameter to the constructor of the exception.

If a generator function defined in the presence of a from __future__
import generator_stop
directive raises StopIteration, it will be
converted into a RuntimeError (retaining the StopIteration
as the new exception’s cause).

Changed in version 3.3: Added value attribute and the ability for generator functions to
use it to return a value.

Changed in version 3.5: Introduced the RuntimeError transformation.

exception StopAsyncIteration

Must be raised by __anext__() method of an
asynchronous iterator object to stop the iteration.

New in version 3.5.

exception SyntaxError

Raised when the parser encounters a syntax error. This may occur in an
import statement, in a call to the built-in functions exec()
or eval(), or when reading the initial script or standard input
(also interactively).

Instances of this class have attributes filename, lineno,
offset and text for easier access to the details. str()
of the exception instance returns only the message.

exception IndentationError

Base class for syntax errors related to incorrect indentation. This is a
subclass of SyntaxError.

exception TabError

Raised when indentation contains an inconsistent use of tabs and spaces.
This is a subclass of IndentationError.

exception SystemError

Raised when the interpreter finds an internal error, but the situation does not
look so serious to cause it to abandon all hope. The associated value is a
string indicating what went wrong (in low-level terms).

You should report this to the author or maintainer of your Python interpreter.
Be sure to report the version of the Python interpreter (sys.version; it is
also printed at the start of an interactive Python session), the exact error
message (the exception’s associated value) and if possible the source of the
program that triggered the error.

exception SystemExit

This exception is raised by the sys.exit() function. It inherits from
BaseException instead of Exception so that it is not accidentally
caught by code that catches Exception. This allows the exception to
properly propagate up and cause the interpreter to exit. When it is not
handled, the Python interpreter exits; no stack traceback is printed. The
constructor accepts the same optional argument passed to sys.exit().
If the value is an integer, it specifies the system exit status (passed to
C’s exit() function); if it is None, the exit status is zero; if
it has another type (such as a string), the object’s value is printed and
the exit status is one.

A call to sys.exit() is translated into an exception so that clean-up
handlers (finally clauses of try statements) can be
executed, and so that a debugger can execute a script without running the risk
of losing control. The os._exit() function can be used if it is
absolutely positively necessary to exit immediately (for example, in the child
process after a call to os.fork()).

code

The exit status or error message that is passed to the constructor.
(Defaults to None.)

exception TypeError

Raised when an operation or function is applied to an object of inappropriate
type. The associated value is a string giving details about the type mismatch.

This exception may be raised by user code to indicate that an attempted
operation on an object is not supported, and is not meant to be. If an object
is meant to support a given operation but has not yet provided an
implementation, NotImplementedError is the proper exception to raise.

Passing arguments of the wrong type (e.g. passing a list when an
int is expected) should result in a TypeError, but passing
arguments with the wrong value (e.g. a number outside expected boundaries)
should result in a ValueError.

exception UnboundLocalError

Raised when a reference is made to a local variable in a function or method, but
no value has been bound to that variable. This is a subclass of
NameError.

exception UnicodeError

Raised when a Unicode-related encoding or decoding error occurs. It is a
subclass of ValueError.

UnicodeError has attributes that describe the encoding or decoding
error. For example, err.object[err.start:err.end] gives the particular
invalid input that the codec failed on.

encoding

The name of the encoding that raised the error.

reason

A string describing the specific codec error.

object

The object the codec was attempting to encode or decode.

start

The first index of invalid data in object.

end

The index after the last invalid data in object.

exception UnicodeEncodeError

Raised when a Unicode-related error occurs during encoding. It is a subclass of
UnicodeError.

exception UnicodeDecodeError

Raised when a Unicode-related error occurs during decoding. It is a subclass of
UnicodeError.

exception UnicodeTranslateError

Raised when a Unicode-related error occurs during translating. It is a subclass
of UnicodeError.

exception ValueError

Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value, and the situation is not described by a
more precise exception such as IndexError.

exception ZeroDivisionError

Raised when the second argument of a division or modulo operation is zero. The
associated value is a string indicating the type of the operands and the
operation.

The following exceptions are kept for compatibility with previous versions;
starting from Python 3.3, they are aliases of OSError.

exception EnvironmentError
exception IOError
exception WindowsError

Only available on Windows.

5.2.1. OS exceptions¶

The following exceptions are subclasses of OSError, they get raised
depending on the system error code.

exception BlockingIOError

Raised when an operation would block on an object (e.g. socket) set
for non-blocking operation.
Corresponds to errno EAGAIN, EALREADY,
EWOULDBLOCK and EINPROGRESS.

In addition to those of OSError, BlockingIOError can have
one more attribute:

characters_written

An integer containing the number of characters written to the stream
before it blocked. This attribute is available when using the
buffered I/O classes from the io module.

exception ChildProcessError

Raised when an operation on a child process failed.
Corresponds to errno ECHILD.

exception ConnectionError

A base class for connection-related issues.

Subclasses are BrokenPipeError, ConnectionAbortedError,
ConnectionRefusedError and ConnectionResetError.

exception BrokenPipeError

A subclass of ConnectionError, raised when trying to write on a
pipe while the other end has been closed, or trying to write on a socket
which has been shutdown for writing.
Corresponds to errno EPIPE and ESHUTDOWN.

exception ConnectionAbortedError

A subclass of ConnectionError, raised when a connection attempt
is aborted by the peer.
Corresponds to errno ECONNABORTED.

exception ConnectionRefusedError

A subclass of ConnectionError, raised when a connection attempt
is refused by the peer.
Corresponds to errno ECONNREFUSED.

exception ConnectionResetError

A subclass of ConnectionError, raised when a connection is
reset by the peer.
Corresponds to errno ECONNRESET.

exception FileExistsError

Raised when trying to create a file or directory which already exists.
Corresponds to errno EEXIST.

exception FileNotFoundError

Raised when a file or directory is requested but doesn’t exist.
Corresponds to errno ENOENT.

exception InterruptedError

Raised when a system call is interrupted by an incoming signal.
Corresponds to errno EINTR.

Changed in version 3.5: Python now retries system calls when a syscall is interrupted by a
signal, except if the signal handler raises an exception (see PEP 475
for the rationale), instead of raising InterruptedError.

exception IsADirectoryError

Raised when a file operation (such as os.remove()) is requested
on a directory.
Corresponds to errno EISDIR.

exception NotADirectoryError

Raised when a directory operation (such as os.listdir()) is requested
on something which is not a directory.
Corresponds to errno ENOTDIR.

exception PermissionError

Raised when trying to run an operation without the adequate access
rights — for example filesystem permissions.
Corresponds to errno EACCES and EPERM.

exception ProcessLookupError

Raised when a given process doesn’t exist.
Corresponds to errno ESRCH.

exception TimeoutError

Raised when a system function timed out at the system level.
Corresponds to errno ETIMEDOUT.

New in version 3.3: All the above OSError subclasses were added.

See also

PEP 3151 — Reworking the OS and IO exception hierarchy

5.3. Warnings¶

The following exceptions are used as warning categories; see the warnings
module for more information.

exception Warning

Base class for warning categories.

exception UserWarning

Base class for warnings generated by user code.

exception DeprecationWarning

Base class for warnings about deprecated features.

exception PendingDeprecationWarning

Base class for warnings about features which will be deprecated in the future.

exception SyntaxWarning

Base class for warnings about dubious syntax.

exception RuntimeWarning

Base class for warnings about dubious runtime behavior.

exception FutureWarning

Base class for warnings about constructs that will change semantically in the
future.

exception ImportWarning

Base class for warnings about probable mistakes in module imports.

exception UnicodeWarning

Base class for warnings related to Unicode.

exception BytesWarning

Base class for warnings related to bytes and bytearray.

exception ResourceWarning

Base class for warnings related to resource usage.

New in version 3.2.

5.4. Exception hierarchy¶

The class hierarchy for built-in exceptions is:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.

Синтаксис обработки исключений

Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.

Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError, которые не стоит пытаться обработать.

Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.

Ошибки могут быть разных видов:

  • Синтаксические
  • Недостаточно памяти
  • Ошибки рекурсии
  • Исключения

Разберем их по очереди.

Синтаксические ошибки (SyntaxError)

Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.

Рассмотрим на примере.

a = 8
b = 10
c = a b
File "", line 3
 c = a b
       ^
SyntaxError: invalid syntax

Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.

Недостаточно памяти (OutofMemoryError)

Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” (heap). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory. Она может появиться по нескольким причинам:

  • Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
  • Загрузка файла большого размера;
  • Запуск модели машинного обучения/глубокого обучения и много другое;

Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError, позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.

Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc()), не факт, что все процессы восстановятся — в некоторых случаях MemoryError приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.

Ошибка рекурсии (RecursionError)

Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.

Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.

Чтобы воспроизвести эту ошибку, определим функцию recursion, которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.

def recursion():
    return recursion()

recursion()
---------------------------------------------------------------------------

RecursionError                            Traceback (most recent call last)

 in 
----> 1 recursion()


 in recursion()
      1 def recursion():
----> 2     return recursion()


... last 1 frames repeated, from the frame below ...


 in recursion()
      1 def recursion():
----> 2     return recursion()


RecursionError: maximum recursion depth exceeded

Ошибка отступа (IndentationError)

Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.

Пример:

for i in range(10):
    print('Привет Мир!')
  File "", line 2
    print('Привет Мир!')
        ^
IndentationError: expected an indented block

Исключения

Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.

Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:

Ошибка типа (TypeError)

a = 2
b = 'PythonRu'
a + b
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      1 a = 2
      2 b = 'PythonRu'
----> 3 a + b


TypeError: unsupported operand type(s) for +: 'int' and 'str'

Ошибка деления на ноль (ZeroDivisionError)

10 / 0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

 in 
----> 1 10 / 0


ZeroDivisionError: division by zero

Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError и ZeroDivisionError. Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.

Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.

Теперь рассмотрим встроенные исключения Python.

Встроенные исключения

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.

  • Try: он запускает блок кода, в котором ожидается ошибка.
  • Except: здесь определяется тип исключения, который ожидается в блоке try (встроенный или созданный).
  • Else: если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).
  • Finally: вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.

В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.

Ошибка прерывания с клавиатуры (KeyboardInterrupt)

Исключение KeyboardInterrupt вызывается при попытке остановить программу с помощью сочетания Ctrl + C или Ctrl + Z в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.

В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt. Теперь обработаем исключение KeyboardInterrupt.

try:
    inp = input()
    print('Нажмите Ctrl+C и прервите Kernel:')
except KeyboardInterrupt:
    print('Исключение KeyboardInterrupt')
else:
    print('Исключений не произошло')

Исключение KeyboardInterrupt

Стандартные ошибки (StandardError)

Рассмотрим некоторые базовые ошибки в программировании.

Арифметические ошибки (ArithmeticError)

  • Ошибка деления на ноль (Zero Division);
  • Ошибка переполнения (OverFlow);
  • Ошибка плавающей точки (Floating Point);

Все перечисленные выше исключения относятся к классу Arithmetic и вызываются при ошибках в арифметических операциях.

Деление на ноль (ZeroDivisionError)

Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.

try:  
    a = 100 / 0
    print(a)
except ZeroDivisionError:  
    print("Исключение ZeroDivisionError." )
else:  
    print("Успех, нет ошибок!")
Исключение ZeroDivisionError.

Переполнение (OverflowError)

Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.

try:  
    import math
    print(math.exp(1000))
except OverflowError:  
    print("Исключение OverFlow.")
else:  
    print("Успех, нет ошибок!")
Исключение OverFlow.

Ошибка утверждения (AssertionError)

Когда инструкция утверждения не верна, вызывается ошибка утверждения.

Рассмотрим пример. Предположим, есть две переменные: a и b. Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert, что приведет к вызову исключения Assertion в том случае, если выражение будет ложным.

try:  
    a = 100
    b = "PythonRu"
    assert a == b
except AssertionError:  
    print("Исключение AssertionError.")
else:  
    print("Успех, нет ошибок!")

Исключение AssertionError.

Ошибка атрибута (AttributeError)

При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes нет атрибута с именем attribute.

class Attributes(obj):
    a = 2
    print(a)

try:
    obj = Attributes()
    print(obj.attribute)
except AttributeError:
    print("Исключение AttributeError.")

2
Исключение AttributeError.

Ошибка импорта (ModuleNotFoundError)

Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.

import nibabel
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

 in 
----> 1 import nibabel


ModuleNotFoundError: No module named 'nibabel'

Ошибка поиска (LookupError)

LockupError выступает базовым классом для исключений, которые происходят, когда key или index используются для связывания или последовательность списка/словаря неверна или не существует.

Здесь есть два вида исключений:

  • Ошибка индекса (IndexError);
  • Ошибка ключа (KeyError);

Ошибка ключа

Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError.

try:  
    a = {1:'a', 2:'b', 3:'c'}  
    print(a[4])  
except LookupError:  
    print("Исключение KeyError.")
else:  
    print("Успех, нет ошибок!")

Исключение KeyError.

Ошибка индекса

Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).

try:
    a = ['a', 'b', 'c']  
    print(a[4])  
except LookupError:  
    print("Исключение IndexError, индекс списка вне диапазона.")
else:  
    print("Успех, нет ошибок!")
Исключение IndexError, индекс списка вне диапазона.

Ошибка памяти (MemoryError)

Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.

Ошибка имени (NameError)

Ошибка имени возникает, когда локальное или глобальное имя не находится.

В следующем примере переменная ans не определена. Результатом будет ошибка NameError.

try:
    print(ans)
except NameError:  
    print("NameError: переменная 'ans' не определена")
else:  
    print("Успех, нет ошибок!")
NameError: переменная 'ans' не определена

Ошибка выполнения (Runtime Error)

Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented. Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.

class BaseClass(object):
    """Опередляем класс"""
    def __init__(self):
        super(BaseClass, self).__init__()
    def do_something(self):
	# функция ничего не делает
        raise NotImplementedError(self.__class__.__name__ + '.do_something')

class SubClass(BaseClass):
    """Реализует функцию"""
    def do_something(self):
        # действительно что-то делает
        print(self.__class__.__name__ + ' что-то делает!')

SubClass().do_something()
BaseClass().do_something()

SubClass что-то делает!



---------------------------------------------------------------------------

NotImplementedError                       Traceback (most recent call last)

 in 
     14
     15 SubClass().do_something()
---> 16 BaseClass().do_something()


 in do_something(self)
      5     def do_something(self):
      6         # функция ничего не делает
----> 7         raise NotImplementedError(self.__class__.__name__ + '.do_something')
      8
      9 class SubClass(BaseClass):


NotImplementedError: BaseClass.do_something

Ошибка типа (TypeError)

Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.

В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.

try:
    a = 5
    b = "PythonRu"
    c = a + b
except TypeError:
    print('Исключение TypeError')
else:
    print('Успех, нет ошибок!')

Исключение TypeError

Ошибка значения (ValueError)

Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.

В этом примере встроенная операция float получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.

try:
    print(float('PythonRu'))
except ValueError:
    print('ValueError: не удалось преобразовать строку в float: 'PythonRu'')
else:
    print('Успех, нет ошибок!')
ValueError: не удалось преобразовать строку в float: 'PythonRu'

Пользовательские исключения в Python

В Python есть много встроенных исключений для использования в программе. Но иногда нужно создавать собственные со своими сообщениями для конкретных целей.

Это можно сделать, создав новый класс, который будет наследовать из класса Exception в Python.

class UnAcceptedValueError(Exception):   
    def __init__(self, data):    
        self.data = data
    def __str__(self):
        return repr(self.data)

Total_Marks = int(input("Введите общее количество баллов: "))
try:
    Num_of_Sections = int(input("Введите количество разделов: "))
    if(Num_of_Sections < 1):
        raise UnAcceptedValueError("Количество секций не может быть меньше 1")
except UnAcceptedValueError as e:
    print("Полученная ошибка:", e.data)

Введите общее количество баллов: 10
Введите количество разделов: 0
Полученная ошибка: Количество секций не может быть меньше 1

В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.

Недостатки обработки исключений в Python

У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.

Дальше пример, где модуль Python timeit используется для проверки времени исполнения 2 разных инструкций. В stmt1 для обработки ZeroDivisionError используется try-except, а в stmt2if. Затем они выполняются 10000 раз с переменной a=0. Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1 с обработкой исключений занимает больше времени чем stmt2, который просто проверяет значение и не делает ничего, если условие не выполнено.

Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.

import timeit
setup="a=0"
stmt1 = '''
try:
    b=10/a
except ZeroDivisionError:
    pass'''

stmt2 = '''
if a!=0:
    b=10/a'''

print("time=",timeit.timeit(stmt1,setup,number=10000))
print("time=",timeit.timeit(stmt2,setup,number=10000))

time= 0.003897680000136461
time= 0.0002797570000439009

Выводы!

Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.

Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try выискивает исключения, а except их обрабатывает.

Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.

In this tutorial, we will learn about exceptions in Python. We will cover exceptions and different types of exceptions in Python.

Video: Python Exception Handling

An exception is an 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 Logical Errors (Exceptions)

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

For instance, they occur when we

  • try to open a file(for reading) that does not exist (FileNotFoundError)
  • try to divide a number by zero (ZeroDivisionError)
  • try to 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. There are plenty of built-in exceptions in Python that are raised 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 are listed below:

Exception Cause of Error
AssertionError Raised when an assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() function hits end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator’s close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when the index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+C or Delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
ReferenceError Raised when a weak reference proxy is used to access a garbage collected referent.
RuntimeError Raised when an error does not fall under any other category.
StopIteration Raised by next() function to indicate that there is no further item to be returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an object of incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
ValueError Raised when a function gets an argument of correct type but improper value.
ZeroDivisionError Raised 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 try, except 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.

June 7, 2022

This tutorial covers exceptions in Python, including why they occur, how to identify them, and how to resolve them.

In this tutorial, we will define exceptions in Python, we will identify why they are important and how they differ from syntax errors, and we will learn how to resolve exceptions in Python.

What Are Exceptions in Python?

When an unexpected condition is encountered while running a Python code, the program stops its execution and throws an error. There are basically two types of errors in Python: syntax errors and exceptions. To understand the difference between these two types, let’s run the following piece of code:

print(x
print(1)
  File "C:UsersUtenteAppDataLocalTemp/ipykernel_4732/4217672763.py", line 2
    print(1)
    ^
SyntaxError: invalid syntax

A syntax error was thrown since we forgot to close the parenthesis. This type of error is always raised when we use a statement that is syntactically incorrect in Python. The parser shows the place where the syntax error was detected by a little arrow ^. Notice also that the subsequent line print(1) was not executed since the Python interpreter stopped working when the error occurred.

Let’s fix this error and re-run the code:

print(x)
print(1)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/971139432.py in 
----> 1 print(x)
      2 print(1)

NameError: name 'x' is not defined

Now when we have fixed the wrong syntax, we got another type of error: an exception. In other words, an exception is a type of error that occurs when a syntactically correct Python code raises an error. An arrow indicates the line where the exception occurred, while the last line of the error message specifies the exact type of exception and provides its description to facilitate debugging. In our case, it is a NameError since we tried to print the value of a variable x that was not defined before. Also in this case, the second line of our piece of code print(1) was not executed because the normal flow of the Python program was interrupted.

To prevent a sudden program crash, it is important to catch and handle exceptions. For example, provide an alternative version of the code execution when the given exception occurs. This is what we are going to learn next.

Standard Built-in Types of Exceptions

Python provides many types of exceptions thrown in various situations. Let’s take a look at the most common built-in exceptions with their examples:

  • NameError – Raised when a name doesn’t exist among either local or global variables:
print(x)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/1353120783.py in 
----> 1 print(x)

NameError: name 'x' is not defined
  • TypeError – Raised when an operation is run on an inapplicable data type:
print(1+'1')
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/218464413.py in 
----> 1 print(1+'1')

TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • ValueError – Raised when an operation or function takes in an invalid value of an argument:
print(int('a'))
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/3219923713.py in 
----> 1 print(int('a'))

ValueError: invalid literal for int() with base 10: 'a'
  • IndexError – Raised when an index doesn’t exist in an iterable:
print('dog'[3])
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/2163152480.py in 
----> 1 print('dog'[3])

IndexError: string index out of range
  • IndentationError – Raised when indentation is incorrect:
for i in range(3):
print(i)
  File "C:UsersUtenteAppDataLocalTemp/ipykernel_4732/3296739069.py", line 2
    print(i)
    ^
IndentationError: expected an indented block
  • ZeroDivisionError – Raised at attempt to divide a number by zero:
print(1/0)
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/165659023.py in 
----> 1 print(1/0)

ZeroDivisionError: division by zero
  • ImportError – Raised when an import statement is incorrect:
from numpy import pandas
---------------------------------------------------------------------------

ImportError                               Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/3955928270.py in 
----> 1 from numpy import pandas

ImportError: cannot import name 'pandas' from 'numpy' (C:UsersUtenteanaconda3libsite-packagesnumpy__init__.py)
  • AttributeError – Raised at attempt to assign or refer an attribute inapplicable for a given Python object:
print('a'.sum())
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/2316121794.py in 
----> 1 print('a'.sum())

AttributeError: 'str' object has no attribute 'sum'
  • KeyError – Raised when the key is absent in the dictionary:
animals = {'koala': 1, 'panda': 2}
print(animals['rabbit'])
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/1340951462.py in 
      1 animals = {'koala': 1, 'panda': 2}
----> 2 print(animals['rabbit'])

KeyError: 'rabbit'

For a full list of Python built-in exceptions, please consult the Python Documentation.

Handling Exceptions in Python

Since raising an exception results in an interruption of the program execution, we have to handle this exception in advance to avoid such undesirable cases.

The try and except Statements

The most basic commands used for detecting and handling exceptions in Python are try and except.

The try statement is used to run an error-prone piece of code and must always be followed by the except statement. If no exception is raised as a result of the try block execution, the except block is skipped and the program just runs as expected. In the opposite case, if an exception is thrown, the execution of the try block is immediately stopped, and the program handles the raised exception by running the alternative code determined in the except block. After that, the Python script continues working and executes the rest of the code.

Let’s see how it works by the example of our initial small piece of code print(x), which raised earlier a NameError:

try:
    print(x)
except:
    print('Please declare the variable x first')

print(1)
Please declare the variable x first
1

Now that we handled the exception in the except block, we received a meaningful customized message of what exactly went wrong and how to fix it. What’s more, this time, the program didn’t stop working as soon as it encountered the exception and executed the rest of the code.

In the above case, we anticipated and handled only one type of exception, more specifically, a NameError. The drawback of this approach is that the piece of code in the except clause will treat all types of exceptions in the same way, and output the same message Please declare the variable x first. To avoid this confusion, we can explicitly mention the type of exception that we need to catch and handle right after the except command:

try:
    print(x)
except NameError:
    print('Please declare the variable x first')
Please declare the variable x first

Handling Multiple Exceptions

Clearly stating the exception type to be caught is needed not only for the sake of code readability. What’s more important, using this approach, we can anticipate various specific exceptions and handle them accordingly.

To understand this concept, let’s take a look at a simple function that sums up the values of an input dictionary:

def print_dict_sum(dct):
    print(sum(dct.values()))

my_dict = {'a': 1, 'b': 2, 'c': 3}
print_dict_sum(my_dict)
6

Trying to run this function, we can have different issues if we accidentally pass to it a wrong input. For example, we can make an error in the dictionary name resulting in an inexistent variable:

print_dict_sum(mydict)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/2473187932.py in 
----> 1 print_dict_sum(mydict)

NameError: name 'mydict' is not defined

Some of the values of the input dictionary can be a string rather than numeric:

my_dict = {'a': '1', 'b': 2, 'c': 3}
print_dict_sum(my_dict)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/2621846538.py in 
      1 my_dict = {'a': '1', 'b': 2, 'c': 3}
----> 2 print_dict_sum(my_dict)

~AppDataLocalTemp/ipykernel_4732/3241128871.py in print_dict_sum(dct)
      1 def print_dict_sum(dct):
----> 2     print(sum(dct.values()))
      3 
      4 my_dict = {'a': 1, 'b': 2, 'c': 3}
      5 print_dict_sum(my_dict)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Another option allows us to pass in an argument of an inappropriate data type for this function:

my_dict = 'a'
print_dict_sum(my_dict)
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/1925769844.py in 
      1 my_dict = 'a'
----> 2 print_dict_sum(my_dict)

~AppDataLocalTemp/ipykernel_4732/3241128871.py in print_dict_sum(dct)
      1 def print_dict_sum(dct):
----> 2     print(sum(dct.values()))
      3 
      4 my_dict = {'a': 1, 'b': 2, 'c': 3}
      5 print_dict_sum(my_dict)

AttributeError: 'str' object has no attribute 'values'

As a result, we have at least three different types of exceptions that should be handled differently: NameError, TypeError, and AttributeError. For this purpose, we can add multiple except blocks (one for each exception type, three in our case) after a single try block:

try: 
    print_dict_sum(mydict)
except NameError:
    print('Please check the spelling of the dictionary name')
except TypeError:
    print('It seems that some of the dictionary values are not numeric')
except AttributeError:
    print('You should provide a Python dictionary with numeric values')
Please check the spelling of the dictionary name

In the code above, we provided a nonexistent variable name as an input to the function inside the try clause. The code was supposed to throw a NameError but it was handled in one of the subsequent except clauses, and the corresponding message was output.

We can also handle the exceptions right inside the function definition. Important: We can’t handle a NameError exception for any of the function arguments since in this case, the exception happens before the function body starts. For example, in the code below:

def print_dict_sum(dct):
    try:
        print(sum(dct.values()))
    except NameError:
        print('Please check the spelling of the dictionary name')
    except TypeError:
        print('It seems that some of the dictionary values are not numeric')
    except AttributeError:
        print('You should provide a Python dictionary with numeric values')

print_dict_sum({'a': '1', 'b': 2, 'c': 3})
print_dict_sum('a')
print_dict_sum(mydict)
It seems that some of the dictionary values are not numeric
You should provide a Python dictionary with numeric values

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/3201242278.py in 
     11 print_dict_sum({'a': '1', 'b': 2, 'c': 3})
     12 print_dict_sum('a')
---> 13 print_dict_sum(mydict)

NameError: name 'mydict' is not defined

The TypeError and AttributeError were successfully handled inside the function and the corresponding messages were output. Instead, because of the above-mentioned reason, the NameError was not handled properly despite introducing a separate except clause for it. Therefore, the NameError for any argument of a function can’t be handled inside the function body.

It is possible to combine several exceptions as a tuple in one except clause if they should be handled in the same way:

def print_dict_sum(dct):
    try:
        print(sum(dct.values()))
    except (TypeError, AttributeError):
        print('You should provide a Python DICTIONARY with NUMERIC values')

print_dict_sum({'a': '1', 'b': 2, 'c': 3})
print_dict_sum('a')
You should provide a Python DICTIONARY with NUMERIC values
You should provide a Python DICTIONARY with NUMERIC values

The else Statement

In addition to the try and except clauses, we can use an optional else command. If present, the else command must be placed after all the except clauses and executed only if no exceptions occurred in the try clause.

For example, in the code below, we tried the division by zero:

try:
    print(3/0)
except ZeroDivisionError:
    print('You cannot divide by zero')
else:
    print('The division is successfully performed')
You cannot divide by zero

The exception was caught and handled in the except block and hence the else clause was skipped. Let’s take a look at what happens if we provide a non-zero number:

try:
    print(3/2)
except ZeroDivisionError:
    print('You cannot divide by zero')
else:
    print('The division is successfully performed')
1.5
The division is successfully performed

Since no exception was raised, the else block was executed and output the corresponding message.

The finally Statement

Another optional statement is finally, if provided, it must be placed after all the clauses including else (if present)
and executed in any case, whether or not an exception was raised in the try clause.

Let’s add the finally block to both of the previous pieces of code and observe the results:

try:
    print(3/0)
except ZeroDivisionError:
    print('You cannot divide by zero')
else:
    print('The division is successfully performed')
finally:
    print('This message is always printed')
You cannot divide by zero
This message is always printed
try:
    print(3/2)
except ZeroDivisionError:
    print('You cannot divide by zero')
else:
    print('The division is successfully performed')
finally:
    print('This message is always printed')
1.5
The division is successfully performed
This message is always printed

In the first case, an exception was raised, in the second there was not. However, in both cases, the finally clause outputs the same message.

Raising an Exception

Sometimes, we may need to deliberately raise an exception and stop the program if a certain condition occurs. For this purpose, we need the raise keyword and the following syntax:

raise ExceptionClass(exception_value)

Above, ExceptionClass is the type of exception to be raised (e.g., TypeError) and exception_value is an optional customized descriptive message that will be displayed if the exception is raised.

Let’s see how it works:

x = 'blue'
if x not in ['red', 'yellow', 'green']:
    raise ValueError
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/2843707178.py in 
      1 x = 'blue'
      2 if x not in ['red', 'yellow', 'green']:
----> 3     raise ValueError

ValueError: 

In the piece of code above, we didn’t provide any argument to the exception and therefore the code didn’t output any message (by default, the exception value is None).

x = 'blue'
if x not in ['red', 'yellow', 'green']:
    raise ValueError('The traffic light is broken')
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_4732/359420707.py in 
      1 x = 'blue'
      2 if x not in ['red', 'yellow', 'green']:
----> 3     raise ValueError('The traffic light is broken')

ValueError: The traffic light is broken

We ran the same piece of code, but this time we provided the exception argument. In this case, we can see an output message that gives more context to why exactly this exception occurred.

Conclusion

In this tutorial, we discussed many aspects regarding exceptions in Python. In particular, we learned the following:

  • How to define exceptions in Python and how they differ from syntax errors
  • What built-in exceptions exist in Python and when they are raised
  • Why it is important to catch and handle exceptions
  • How to handle one or multiple exceptions in Python
  • How different clauses for catching and handling exceptions work together
  • Why it’s important to specify the type of exception to be handled
  • Why we can’t handle a NameError for any argument of a function inside the function definition
  • How to raise an exception
  • How to add a descriptive message to a raised exception and why it is a good practice

With these skills, you’re ready to cope with any real-world data science tasks that require resolving exceptions in Python.

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program. 
    Two types of Error occurs in python. 
     

    1. Syntax errors
    2. Logical errors (Exceptions) 
       

    Syntax errors

    When the proper syntax of the language is not followed then a syntax error is thrown.
    Example 
     

    Python3

    amount = 10000

    if(amount>2999)

        print("You are eligible to purchase Dsa Self Paced")

    Output:
     

    It returns a syntax error message because after the if statement a colon: is missing. We can fix this by writing the correct syntax.
     

    logical errors(Exception)

    When in the runtime an error that occurs after passing the syntax test is called exception or logical type. For example, when we divide any number by zero then the ZeroDivisionError exception is raised, or when we import a module that does not exist then ImportError is raised.
    Example 1: 
     

    Python3

    marks = 10000

    a = marks / 0

    print(a)

    Output:
     

    In the above example the ZeroDivisionError as we are trying to divide a number by 0.
    Example 2: When indentation is not correct. 
     

    Python3

    Output:
     

    Some of the common built-in exceptions are other than above mention exceptions are:
     

    Exception Description
    IndexError When the wrong index of a list is retrieved.
    AssertionError It occurs when the assert statement fails
    AttributeError It occurs when an attribute assignment is failed.
    ImportError It occurs when an imported module is not found.
    KeyError It occurs when the key of the dictionary is not found.
    NameError It occurs when the variable is not defined.
    MemoryError It occurs when a program runs out of memory.
    TypeError It occurs when a function and operation are applied in an incorrect type.

    Note: For more information, refer to Built-in Exceptions in Python
     

    Error Handling

    When an error and an exception are raised then we handle that with the help of the Handling method.
     

    • Handling Exceptions with Try/Except/Finally 
      We can handle errors by the Try/Except/Finally method. we write unsafe code in the try, fall back code in except and final code in finally block.
      Example 
       

    Python3

    try:

         print("code start")

         print(1 / 0)

    except:

         print("an error occurs")

    finally:

         print("GeeksForGeeks")

    • Output: 
       
    code start
    an error occurs
    GeeksForGeeks
    •  
    • Raising exceptions for a predefined condition 
      When we want to code for the limitation of certain conditions then we can raise an exception. 
      Example 
       

    Python3

    try:

        amount = 1999

        if amount < 2999:

            raise ValueError("please add money in your account")

        else:

            print("You are eligible to purchase DSA Self Paced course")

    except ValueError as e:

            print(e)

    • Output: 
       
    please add money in your account

    Понравилась статья? Поделить с друзьями:
  • Python except socket error
  • Python except exception error
  • Python error петька 6
  • Python error unindent does not match any outer indentation level
  • Python error running main