Lista de excepciones de python

Ejemplos de código

31
0

lista de excepciones de python

AssertionError			#Raised when assert statement fails.
AttributeError			#Raised when attribute assignment or reference fails.
EOFError				#Raised when the input() functions 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 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 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 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 argument of correct type but improper value.
ZeroDivisionError		#Raised when second operand of division or modulo operation is zero.
15
0

excepción de python

try:
  # code block
except ValueError as ve:
  print(ve)
8
0

tipos de excepción 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
3
0

excepción de python

try:
   # Code to test / execute
   print('Test')
except (SyntaxError, IndexError) as E:  # specific exceptions
   # Code in case of SyntaxError for example
   print('Synthax or index error !')
except :
   # Code for any other exception
   print('Other error !')
else:
   # Code if no exception caught
   print('No error')
finally:
   # Code executed after try block (success) or any exception (ie everytime)
   print('Done')

# This code is out of try / catch bloc
print('Anything else')
0
0

error de índice en python

# main.py
import datetime

from gw_utility.book import Book
from gw_utility.logging import Logging


def main():
    try:
        # Create list and populate with Books.
        books = list()
        books.append(Book("Shadow of a Dark Queen", "Raymond E. Feist", 497, datetime.date(1994, 1, 1)))
        books.append(Book("Rise of a Merchant Prince", "Raymond E. Feist", 479, datetime.date(1995, 5, 1)))
        books.append(Book("Rage of a Demon King", "Raymond E. Feist", 436, datetime.date(1997, 4, 1)))

        # Output Books in list, with and without index.
        Logging.line_separator('Books')
        log_list(books)
        Logging.line_separator('Books w/ index')
        log_list(books, True)
        # Output list element outside bounds.
        Logging.line_separator('books[len(books)]')
        Logging.log(f'books[{len(books)}]: {books[len(books)]}')
    except IndexError as error:
        # Output expected IndexErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)


def log_list(collection, include_index=False):
    """Logs the each element in collection to the console.

    :param collection: Collection to be iterated and output.
    :param include_index: Determines if index is also output.
    :return: None
    """
    try:
        # Iterate by converting to enumeration.
        for index, item in enumerate(collection):
            if include_index:
                Logging.log(f'collection[{index}]: {item}')
            else:
                Logging.log(item)
    except IndexError as error:
        # Output expected IndexErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)


if __name__ == "__main__":
    main()
-2
0

python: error de subida

class MyError(TypeError):
    pass

raise MyError('An error happened')

Páginas relacionadas

Páginas de ejemplo relacionadas

En otros idiomas

Esta página está en otros idiomas

Русский
..................................................................................................................
English
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Slovenský
..................................................................................................................
Балгарскі
..................................................................................................................
Íslensk
..................................................................................................................