Python Track · Part 6 of 9

Python Exceptions: try, except and finally

Python
Exceptions
Handle errors in Python with try, except and finally, raise custom exceptions, and understand the exception class hierarchy.
Author

Gujuri Alekha

Published

Oct 20, 2024

6.1 Handling Exceptions (try, except, finally)

Try-Except Block: In Python, you can use a try block to enclose the code that might raise an exception. If an exception occurs within the try block, the program immediately jumps to the corresponding except block.

Show code
try:
    result = 10 / 0  # This will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Cannot divide by zero.")

Finally Block: You can also include a finally block after the try and except blocks. Code inside the finally block will always run, whether an exception occurred or not. It’s typically used for cleanup operations like closing files or network connections.

Show code
try:
    # Code that may raise an exception
except ExceptionType:
    # Code to handle the exception
finally:
    # Code that always runs

6.2 Raising Custom Exceptions

  • Sometimes, you may want to raise your own exceptions to handle specific situations in your code. To do this, you can create a custom exception class by inheriting from the built-in Exception class or one of its subclasses. Here’s how you can raise a custom exception:
Show code
class MyCustomException(Exception):
    pass

try:
    # Some code
    if something_bad_happens:
        raise MyCustomException("An error occurred")
except MyCustomException as e:
    print(f"Custom exception caught: {e}")

6.3 Exception Hierarchy

  • Python has a hierarchy of exception classes, with the base class being BaseException. This class is the parent of all built-in exceptions. More specific exceptions inherit from higher-level exceptions, which allows you to catch exceptions at different levels of granularity.
  • ArithmeticError is a subclass of BaseException and is the parent class of exceptions like ZeroDivisionError.
  • ZeroDivisionError is a subclass of ArithmeticError.

Citation

BibTeX citation:
@online{alekha2024,
  author = {Alekha, Gujuri},
  title = {Python {Exceptions:} Try, Except and Finally},
  date = {2024-10-20},
  url = {https://gujurialekha.github.io/blog/python/06-python-error-handling-and-exceptions.html},
  langid = {en}
}