Title: A Gentle Intro to Exception Handling in Python

  • LLMs Do Not Have Memory
  • Prompting Techniques for Better Reasoning
  • Multi-action within a Prompt
  • Prompt Chaining
  • Exception Handling
  • Hands-on Walkthrough and Tasks




  • ✦ Exception handling is a fundamental skill for every Python programmer. It allows programmers to handle errors and unexpected situations that can arise during program execution.

  • ✦ In this note, we’ll explore how to handle these unexpected situations in Python.

    • We’ll look at tools like ‘try’ and ‘except’, which let us plan for things that could go wrong.
    • We’ll also talk about ‘finally’, which is something we can use to clean up after an issue occurs.
    • We’ll even show you how to create your own exceptions, like making a custom warning when you’re about to run out of glue!
  • ✦ By the end of this note, you’ll learn how to handle errors without having your application crashes or stops abruptly, making your applications more reliable.

    • These are part of the important skills for building great applications with Python, Streamlit, OpenAI API, and of course even a generic Python script.



Overall Structure

Here is the basic structure of the Exception Handling

# Step 1: Understand the basic structure
try:
    # Code that might raise an exception
    <..>
except ExceptionType:
    # Code to handle the exception
    <..>
finally:
    # Code to be executed regardless of whether an exception was raised
    <..>




Try and Except:

Python’s try and except statements provide a safety net for your code, allowing you to catch and handle exceptions that might occur during execution. This prevents your program from crashing and provides an opportunity to recover gracefully.

try:  
	dividend = 10  
	divisor = 0  
	result = dividend / divisor  
except:
	print("Error: Division by zero is not allowed.")
	



finally:

The finally the block is used in conjunction with try and except to define cleanup actions that should be performed, regardless of whether an exception occurs or not.

try:
    # Attempt to divide 10 by a variable that may be zero
	dividend = 10  
	divisor = 0  
	result = dividend / divisor  
    
except:
    # Handle the error if the divisor is zero
    print("Error: Cannot divide by zero.")
    
finally:
    # This block will execute no matter what
    print("Division attempt finished.")

In this scenario, the file is opened, and the content is read. If an exception occurs, it is caught and handled. Regardless of the outcome, the finally block ensures that the file is properly closed, preventing resource leaks.




Exceptions Types

Python provides a comprehensive set of built-in exceptions to handle a wide range of errors and exceptional conditions that can occur during program execution. These exceptions are organized into a hierarchy, with the base class BaseException at the top. Here are some commonly used built-in exceptions along with a brief description

These are just a few examples of the many built-in exceptions that Python provides.

  • Each exception carries specific information about the error, which can be accessed using try and except blocks to handle them gracefully and provide meaningful feedback to the user.

Here is the example of when we incorporate these specific Exception type into our earlier code:

try:  
	dividend = 10  
	divisor = 0  
	result = dividend / divisor  

except ZeroDivisionError:
	print("Error: Division by zero is not allowed.")
	

Here is another example.

try:
    # Attempt to access a key that may not exist in the dictionary
    my_dict = {'a': 1, 'b': 2}
    value = my_dict['c']
    
except KeyError:
    # Handle the error if the key 'c' does not exist
    print("Error: Key not found in the dictionary.")
    
finally:
    # This block will execute regardless of the previous outcome
    print("Key lookup attempt finished.")