Language: EN

excepciones-en-python

Exceptions in Python

In Python, exceptions are events that disrupt the normal flow of execution of a program when an error occurs.

Exceptions are used to signal exceptional conditions that require special handling, such as division by zero, referencing an undefined variable, or opening a file that does not exist.

Some characteristics of exceptions are:

  • Disruption of Normal Flow: Exceptions alter the normal flow of the program.
  • Custom Handling: They allow for specific and controlled error handling.
  • Class Inheritance: Exceptions in Python are classes, allowing the creation of exception hierarchies.

Base Exceptions

In Python, all exceptions inherit from the base exceptions,

  • Exception: Base class for all exceptions in Python, except those that indicate interpreter exit.
  • BaseException: Base class for all exceptions, including those used to control program termination.

Standard Exceptions in Python

Python includes a wide range of standard exceptions that cover various errors and exceptional conditions. Here’s a list of some of the most common standard exceptions.

Runtime Error Exceptions

try:
    result = 1 / 0
except ZeroDivisionError as e:
    print(f"Division by zero error: {e}")
  • ArithmeticError: Base class for numeric errors.
  • ZeroDivisionError: Raised when attempting to divide by zero.
  • OverflowError: Raised when a numeric calculation exceeds the maximum limit allowed.
  • FloatingPointError: Raised when a floating-point operation fails.

Input/Output Operation Exceptions

try:
    with open('non_existent_file.txt', 'r') as file:
        content = file.read()
except FileNotFoundError as e:
    print(f"File not found: {e}")
  • IOError: Base class for input/output errors.
  • FileNotFoundError: Raised when a file or directory is not found.
  • PermissionError: Raised when an operation lacks the proper permissions.

Argument Exceptions

try:
    number = int("abc")
except ValueError as e:
    print(f"Value error: {e}")
  • TypeError: Raised when an operation or function is applied to an inappropriate type of object.
  • ValueError: Raised when an operation or function receives an argument of the correct type but an inappropriate value.

Variable and Attribute Exceptions

try:
    print(undefined_variable)
except NameError as e:
    print(f"Variable name not found: {e}")
  • NameError: Raised when a local or global variable is not found.
  • AttributeError: Raised when trying to access an attribute that does not exist on an object.

System Exceptions

  • SystemError: Raised when an internal error in Python is detected.
  • KeyboardInterrupt: Raised when the program’s execution is interrupted by user input (for example, Ctrl+C).