Python wrong argument exception

8. Errors and Exceptions¶

Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.

8.1. Syntax Errors¶

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:

The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the function print() , since a colon ( ‘:’ ) is missing before it. File name and line number are printed so you know where to look in case the input came from a script.

8.2. Exceptions¶

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:

The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError , NameError and TypeError . The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception occurred, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.

Built-in Exceptions lists the built-in exceptions and their meanings.

8.3. Handling Exceptions¶

It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control — C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

The try statement works as follows.

First, the try clause (the statement(s) between the try and except keywords) is executed.

If no exception occurs, the except clause is skipped and execution of the try statement is finished.

If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.

If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order:

Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.

When an exception occurs, it may have associated values, also known as the exception’s arguments. The presence and types of the arguments depend on the exception type.

The except clause may specify a variable after the exception name. The variable is bound to the exception instance which typically has an args attribute that stores the arguments. For convenience, builtin exception types define __str__() to print all the arguments without explicitly accessing .args .

The exception’s __str__() output is printed as the last part (‘detail’) of the message for unhandled exceptions.

BaseException is the common base class of all exceptions. One of its subclasses, Exception , is the base class of all the non-fatal exceptions. Exceptions which are not subclasses of Exception are not typically handled, because they are used to indicate that the program should terminate. They include SystemExit which is raised by sys.exit() and KeyboardInterrupt which is raised when a user wishes to interrupt the program.

Exception can be used as a wildcard that catches (almost) everything. However, it is good practice to be as specific as possible with the types of exceptions that we intend to handle, and to allow any unexpected exceptions to propagate on.

The most common pattern for handling Exception is to print or log the exception and then re-raise it (allowing a caller to handle the exception as well):

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.

Exception handlers do not handle only exceptions that occur immediately in the try clause, but also those that occur inside functions that are called (even indirectly) in the try clause. For example:

8.4. Raising Exceptions¶

The raise statement allows the programmer to force a specified exception to occur. For example:

The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from BaseException , such as Exception or one of its subclasses). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:

If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:

8.5. Exception Chaining¶

If an unhandled exception occurs inside an except section, it will have the exception being handled attached to it and included in the error message:

To indicate that an exception is a direct consequence of another, the raise statement allows an optional from clause:

This can be useful when you are transforming exceptions. For example:

It also allows disabling automatic exception chaining using the from None idiom:

For more information about chaining mechanics, see Built-in Exceptions .

8.6. User-defined Exceptions¶

Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derived from the Exception class, either directly or indirectly.

Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception.

Читайте также:  Extensions conf asterisk reload

Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions.

Many standard modules define their own exceptions to report errors that may occur in functions they define.

8.7. Defining Clean-up Actions¶

The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:

If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception. The following points discuss more complex cases when an exception occurs:

If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.

An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.

If the finally clause executes a break , continue or return statement, exceptions are not re-raised.

If the try statement reaches a break , continue or return statement, the finally clause will execute just prior to the break , continue or return statement’s execution.

If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement.

A more complicated example:

As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.

In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.

8.8. Predefined Clean-up Actions¶

Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen.

The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.

After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.

8.9. Raising and Handling Multiple Unrelated Exceptions¶

There are situations where it is necessary to report several exceptions that have occurred. This is often the case in concurrency frameworks, when several tasks may have failed in parallel, but there are also other use cases where it is desirable to continue execution and collect multiple errors rather than raise the first exception.

The builtin ExceptionGroup wraps a list of exception instances so that they can be raised together. It is an exception itself, so it can be caught like any other exception.

By using except* instead of except , we can selectively handle only the exceptions in the group that match a certain type. In the following example, which shows a nested exception group, each except* clause extracts from the group exceptions of a certain type while letting all other exceptions propagate to other clauses and eventually to be reraised.

Note that the exceptions nested in an exception group must be instances, not types. This is because in practice the exceptions would typically be ones that have already been raised and caught by the program, along the following pattern:

8.10. Enriching Exceptions with Notes¶

When an exception is created in order to be raised, it is usually initialized with information that describes the error that has occurred. There are cases where it is useful to add information after the exception was caught. For this purpose, exceptions have a method add_note(note) that accepts a string and adds it to the exception’s notes list. The standard traceback rendering includes all notes, in the order they were added, after the exception.

For example, when collecting exceptions into an exception group, we may want to add context information for the individual errors. In the following each exception in the group has a note indicating when this error has occurred.


5. Built-in Exceptions¶

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 :

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.

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.

Читайте также:  Playstation one с прошивкой

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.

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:

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

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

Raised when a buffer related operation cannot be performed.

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.

Raised when an assert statement fails.

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.)

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

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.

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.

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.

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.

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.)

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

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.

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.

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.

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.

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 .

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

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.

A numeric error code from the C variable errno .

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.

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

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.

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.

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.

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.

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.

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).

Читайте также:  Samsung n9005 кастомные прошивки

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.

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

New in version 3.5.

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.

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

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

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.

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() ).

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

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 .

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 .

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.

The name of the encoding that raised the error.

A string describing the specific codec error.

The object the codec was attempting to encode or decode.

The first index of invalid data in object .

The index after the last invalid data in object .

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

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

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

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 .

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.

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:

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.

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

A base class for connection-related issues.

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 .

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

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

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

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

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

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 .

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

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

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

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

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.

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.

Base class for warning categories.

Base class for warnings generated by user code.

Base class for warnings about deprecated features.

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

Base class for warnings about dubious syntax.

Base class for warnings about dubious runtime behavior.

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

Base class for warnings about probable mistakes in module imports.

Base class for warnings related to Unicode.

Base class for warnings related to bytes and bytearray .

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: