Mastering Python Built-in Exceptions for Robust Programming

Python Built-in Exceptions

Python provides a variety of built-in exceptions that help handle errors and manage the flow of a program. Understanding these exceptions is crucial for writing robust and reliable code.

Key Concepts

  • Exceptions: These are events that disrupt the normal flow of a program. When an error occurs, Python raises an exception.
  • Handling Exceptions: You can handle exceptions using try, except, else, and finally blocks to prevent your program from crashing.

Common Built-in Exceptions

Here are some of the most common built-in exceptions in Python:

  • NameError: Raised when a variable is not defined.
    • Example:
    • print(x) # Raises NameError if x is not defined
  • TypeError: Raised when an operation or function is applied to an object of inappropriate type.
    • Example:
    • print('2' + 2) # Raises TypeError because you can't add str and int
  • ValueError: Raised when a function receives an argument of the right type but an inappropriate value.
    • Example:
    • int('abc') # Raises ValueError because 'abc' cannot be converted to int
  • IndexError: Raised when trying to access an index that is out of range in a list.
    • Example:
    • my_list = [1, 2, 3]
      print(my_list[5]) # Raises IndexError
  • KeyError: Raised when trying to access a dictionary with a key that doesn’t exist.
    • Example:
    • my_dict = {'a': 1}
      print(my_dict['b']) # Raises KeyError

Exception Handling Structure

  • Try Block: Contains code that may raise an exception.
  • Except Block: Contains code that executes if an exception occurs.
  • Else Block: Executes if the try block does not raise an exception.
  • Finally Block: Executes regardless of whether an exception occurred or not.

Example of Exception Handling

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")
else:
    print("Division successful:", result)
finally:
    print("Execution completed.")

Conclusion

Understanding built-in exceptions in Python helps you write better error-handling code. By using try and except blocks, you can manage errors gracefully and ensure your program runs smoothly.