Python Standard Error Types
Contents |
This module never needs to be imported explicitly: the exceptions are provided in the built-in namespace as well as the exceptions module. python valueerror example For class exceptions, in a try statement with an except python filenotfounderror clause that mentions a particular class, that clause also handles any exception classes derived from that class python custom exception (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 python exception message 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 containing several items of information (e.g., an error code and a string explaining the code). The associated value is the second
Python Exception Class Methods
argument to the raise statement. If the exception class is derived from the standard root class BaseException, the associated value is present as the exception instance's args attribute. 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. The following exceptions are only used 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() or unicode() is call
Historically (until release 2.2), Python's built-in types have differed from user-defined types because it was not possible to use
Python Errno
the built-in types as the basis for object-oriented inheritance. This limitation python attributeerror object has no attribute no longer exists. The principal built-in types are numerics, sequences, mappings, files, classes, instances and exceptions. assertionerror python Some operations are supported by several object types; in particular, practically all objects can be compared, tested for truth value, and converted to a string (with https://docs.python.org/2/library/exceptions.html the repr() function or the slightly different list3 function). The latter function is implicitly used when an object is written by the list2 function. 5.1. Truth Value Testing¶ Any object can be tested for truth value, for use in an list1 or list0 condition or as operand of the Boolean https://docs.python.org/2/library/stdtypes.html operations below. The following values are considered false: tuple9 tuple8 zero of any numeric type, for example, tuple7, tuple6, tuple5, tuple4. any empty sequence, for example, tuple3, tuple2, tuple1. any empty mapping, for example, tuple0. instances of user-defined classes, if the class defines a bytearray9 or bytearray8 method, when that method returns the integer zero or bytearray7 value bytearray6. [1] All other values are considered true -- so objects of many types are always true. Operations and built-in functions that have a Boolean result always return bytearray5 or bytearray4 for false and bytearray3 or bytearray2 for true, unless otherwise stated. (Important exception: the Boolean operations bytearray1 and bytearray0 always return one of their operands.) 5.2. Boolean Operations -- buffer9, buffer8, buffer7¶ These are the Boolean operations, ordered by ascending priority: Operation Result Notes Exception StandardError ArithmeticError LookupError EnvironmentError Raised Exceptions AssertionError AttributeError EOFError FloatingPointError GeneratorExit IOError ImportError IndexError KeyError KeyboardInterrupt MemoryError NameError NotImplementedError OSError https://pymotw.com/2/exceptions/ OverflowError ReferenceError RuntimeError StopIteration SyntaxError SystemError SystemExit TypeError UnboundLocalError UnicodeError ValueError http://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python ZeroDivisionError Warning Categories Navigation Table of Contents Previous: Built-in Objects Next: String Services This Page Show Source Examples The output from all the example programs from PyMOTW has been generated with Python 2.7.8, unless otherwise noted. Some of the features described here may not be available in python exception earlier versions of Python. If you are looking for examples that work under Python 3, please refer to the PyMOTW-3 section of the site. Navigation index modules | next | previous | PyMOTW » Built-in Objects » exceptions - Built-in error classes¶ Purpose:The exceptions module defines the built-in errors used throughout the standard library and by the interpreter. Available python standard error In:1.5 and later Description¶ In the past, Python has supported simple string messages as exceptions as well as classes. Since 1.5, all of the standard library modules use classes for exceptions. Starting with Python 2.5, string exceptions result in a DeprecationWarning, and support for string exceptions will be removed in the future. Base Classes¶ The exception classes are defined in a hierarchy, described in the standard library documentation. In addition to the obvious organizational benefits, exception inheritance is useful because related exceptions can be caught by catching their base class. In most cases, these base classes are not intended to be raised directly. BaseException¶ Base class for all exceptions. Implements logic for creating a string representation of the exception using str() from the arguments passed to the constructor. Exception¶ Base class for exceptions that do not result in quitting the running application. All user-defined exceptions should use Exception as a base class. StandardError¶ Base class for built-in exceptions used in the standard library. ArithmeticError¶ Base class for math-related errors. LookupError¶ Base class for errors here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Manually raising (throwing) an exception in Python up vote 800 down vote favorite 189 How can I raise an exception in Python so that it can later be caught via an except block? python exception exception-handling share|improve this question edited Feb 3 '15 at 14:37 DavidRR 5,20472747 asked Jan 12 '10 at 21:07 TIMEX 41.2k201525826 add a comment| 3 Answers 3 active oldest votes up vote 787 down vote accepted How do I manually throw/raise an exception in Python? Use the most specific Exception constructor that semantically fits your issue. Be specific in your message, e.g.: raise ValueError('A very specific bad thing happened') Don't do this: Avoid raising a generic Exception, to catch it, you'll have to catch all other more specific exceptions that subclass it. Hiding bugs raise Exception('I know Python!') # don't, if you catch, likely to hide bugs. For example: def demo_bad_catch(): try: raise ValueError('represents a hidden bug, do not catch this') raise Exception('This is the exception you expect to handle') except Exception as error: print('caught this error: ' + repr(error)) >>> demo_bad_catch() caught this error: ValueError('represents a hidden bug, do not catch this',) Won't catch and more specific catches won't catch the general exception: def demo_no_catch(): try: raise Exception('general exceptions not caught by specific handling') except ValueError as e: print('we will not catch e') >>> demo_no_catch() Traceback (most recent call last): File "