excepciones-en-python

Exceptions in Python

  • 3 min

In Python, exceptions are events that represent an error, and which interrupt the normal execution flow of a program.

Exceptions are used to signal exceptional conditions that require special handling (for example, division by zero, reference to an undefined variable, or opening a file that does not exist).

Some characteristics of exceptions are:

  • Interruption of normal flow: Exceptions alter the normal flow of the program.
  • Custom exceptions: They allow handling errors in a specific and controlled manner.
  • Exception inheritance: Exceptions in Python are classes (this allows creating hierarchies of exceptions).

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 large number of standard exceptions that cover various errors and exceptional conditions. Let’s go through 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}")
Copied!
  • ArithmeticError: Base class for numeric errors
  • ZeroDivisionError: Raised when attempting to divide by zero
  • OverflowError: Raised when a numeric calculation exceeds the maximum allowed limit
  • FloatingPointError: Raised when an error occurs in a floating-point operation

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}")
Copied!
  • IOError: Base class for input/output errors
  • FileNotFoundError: Raised when a file or directory is not found
  • PermissionError: Raised when an operation lacks the appropriate permissions

Argument Exceptions

try:
    number = int("abc")
except ValueError as e:
    print(f"Value error: {e}")
Copied!
  • TypeError: Raised when an operation or function is applied to an object of inappropriate type
  • ValueError: Raised when an operation or function receives an argument with 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}")
Copied!
  • 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 program execution is interrupted by user input (for example, Ctrl+C)