The Python Journey – Chapter V Python Exceptions Handling

Python Exception Handling

Python Exceptions Handling: A Detailed Guide with Examples

Exceptions handling is expected from any modern day programming language. Python is not an exception 😉 Python’s exception handling mechanism provides a structured way to manage errors that occur during the execution of a program. Without exception handling, an error would typically terminate the program, but by handling exceptions, you can gracefully manage these errors, allowing the program to continue running or provide meaningful error messages. These are an asset for the end programmers who would want to eventually look into the issue and fix it.

In the last article we learned about type casting in Python – You can access the article here. In this article (which obviously is going to be long) , we’ll explore the fundamentals of Python’s exception handling, the common types of exceptions that can occur, and how to handle them using try, except, else, and finally blocks. We’ll also provide examples of different types of exceptions to help you understand how they work in real-world scenarios.

Table Of Contents

Chapter V Python Exceptions Handling.

Python Exception Handling: A Detailed Guide with Examples.

What is Exception Handling?.

Basic Exception Handling with try-except

Handling Multiple Exceptions.

Using else and finally.

Common Python Exceptions and How to Handle Them..

1 ZeroDivisionError

2 ValueError

3 TypeError

4 IndexError

5 KeyError

6 FileNotFoundError

7 AttributeError

8 NameError

9 IndentationError

10 SyntaxError

Raising Exceptions.

Creating Custom Exceptions.

Conclusion.


What is Exception Handling?

An exception is an event that occurs during the execution of a program and disrupts the normal flow of instructions. Exceptions are raised when errors are encountered, such as division by zero, accessing an index that doesn’t exist in a list, or attempting to open a file that doesn’t exist.

Python uses a system of try-except blocks to catch and handle exceptions. This allows developers to manage these errors gracefully, preventing program crashes and ensuring a smoother user experience.


Basic Exception Handling with try-except

The simplest form of exception handling involves using the try and except blocks. When a block of code inside a try block raises an exception, Python looks for the appropriate except block to handle the error.

Syntax:

try:

    # Code that might raise an exception

except ExceptionType:

    # Code that runs if the exception occurs

Example:

try:

    result = 10 / 0  # This will raise a ZeroDivisionError

except ZeroDivisionError:

    print("Cannot divide by zero!")

In this example, the division operation attempts to divide by zero, which raises a ZeroDivisionError. The except block catches the error and prints a message instead of crashing the program.

Python exception handling

Handling Multiple Exceptions

In Python, you can handle multiple exceptions by specifying different except blocks for each exception type. This allows you to provide specific handling for different types of errors.

Syntax:

try:

    # Code that might raise an exception

except ExceptionType1:

    # Code to handle ExceptionType1

except ExceptionType2:

    # Code to handle ExceptionType2

Example:

try:

    number = int(input("Enter a number: "))

    result = 10 / number

except ValueError:

    print("Invalid input! Please enter a valid integer.")

except ZeroDivisionError:

    print("You cannot divide by zero.")

In this example:

  • If the user enters a non-integer value, a ValueError is raised, and the program prints an error message.
  • If the user enters 0, a ZeroDivisionError is raised, and a specific message is printed for that case.

Using else and finally

Python also provides the else and finally blocks, which can be used in conjunction with try-except to provide additional functionality.

  • else block: The code inside the else block runs if no exceptions occur in the try block.
  • finally block: The finally block contains code that runs regardless of whether an exception occurs or not. It’s typically used for cleanup tasks, such as closing files or releasing resources.

Syntax:

try:

    # Code that might raise an exception

except ExceptionType:

    # Code that runs if an exception occurs

else:

    # Code that runs if no exception occurs

finally:

    # Code that always runs

Example:

try:

    file = open("example.txt", "r")

    content = file.read()

except FileNotFoundError:

    print("The file does not exist.")

else:

    print("File read successfully!")

finally:

    file.close()

    print("File is now closed.")

In this example:

  • The else block runs if the file is successfully opened and read.
  • The finally block ensures that the file is closed, regardless of whether an exception occurred.

Afford the new style statement. Get the new Luxury. All New Apple iPhone 16 (128 GB) – Black ₹79,900


Common Python Exceptions and How to Handle Them

Python provides a wide range of built-in exceptions. Here is a list of common exceptions that you may encounter, along with descriptions and examples of how to handle them.

1 ZeroDivisionError

This exception is raised when you try to divide a number by zero.

Example:

try:

    result = 10 / 0

except ZeroDivisionError:

    print("Cannot divide by zero!")

2 ValueError

This exception occurs when an operation receives an argument of the correct type but an inappropriate value, such as converting a non-numeric string to an integer.

Example:

try:

    number = int("abc")  # This will raise a ValueError

except ValueError:

    print("Invalid value. Please enter a valid number.")

3 TypeError

This exception is raised when an operation or function is applied to an object of an inappropriate type.

Example:

try:

    result = "abc" + 123  # This will raise a TypeError

except TypeError:

    print("You cannot add a string and an integer!")

4 IndexError

This exception is raised when you try to access an element from a list or tuple using an index that is out of range.

Example:

my_list = [1, 2, 3]

try:

    element = my_list[5]  # This will raise an IndexError

except IndexError:

    print("Index out of range!")

5 KeyError

This exception is raised when a dictionary key is not found in the dictionary.

Example:

my_dict = {"name": "Alice", "age": 25}

try:

    print(my_dict["address"])  # This will raise a KeyError

except KeyError:

    print("Key not found in the dictionary!")

HP Laptop 15, 12th Gen i3-1215U, 15.6-inch (39.6 cm), FHD, Anti-Glare, 8GB DDR4, 512GB SSD, Intel UHD Graphics, Dual Speakers, (Win 11, MSO 2021, Silver, 1.69 kg), 15s-fy5006TU

28% OFF @  ₹35,999

6 FileNotFoundError

This exception is raised when attempting to open a file that does not exist.

Example:

try:

    file = open("non_existent_file.txt", "r")

except FileNotFoundError:

    print("The file does not exist!")

7 AttributeError

This exception is raised when an invalid attribute reference is made, such as calling a method or attribute that doesn’t exist for a particular object.

Example:

my_list = [1, 2, 3]

try:

    my_list.append(4)

    my_list.push(5)  # This will raise an AttributeError

except AttributeError:

    print("The method you are trying to use does not exist!")

8 NameError

This exception occurs when a variable or function is referenced before it has been assigned or defined.

Example:

try:

    print(x)  # This will raise a NameError because x is not defined

except NameError:

    print("Variable is not defined!")

9 IndentationError

This occurs when Python’s strict indentation rules are violated.

Example:

try:

    # Improper indentation will cause an IndentationError

    def my_function():

    print("Hello")  # This line is improperly indented

except IndentationError:

    print("Check your indentation!")

10 SyntaxError

This exception is raised when the parser encounters a syntax error.

Example:

try:

    eval('5 +')  # This will raise a SyntaxError

except SyntaxError:

    print("There is a syntax error in your code!")

Python Exception Handling

Raising Exceptions

You can also raise exceptions manually using the raise keyword when certain conditions occur in your program that you want to handle explicitly.

Example:

def check_positive(number):

    if number < 0:

        raise ValueError("The number cannot be negative!")

    return number

try:

    print(check_positive(-5))

except ValueError as e:

    print(e)

In this example, if the number is negative, the program raises a ValueError with a custom error message.


Creating Custom Exceptions

Python is flexible enough to let you create custom exceptions.

In Python, you can create your own exceptions by defining a new exception class that inherits from the built-in Exception class. This allows you to raise more specific exceptions in your programs.

Example:

class NegativeNumberError(Exception):

    pass

def check_positive(number):

    if number < 0:

        raise NegativeNumberError(“Negative numbers are not allowed!”)

    return number

try:

    check_positive(-10)

except NegativeNumberError as e:

    print(e)

In this example, the NegativeNumberError is a custom exception that is raised when a negative number is provided as input.


Conclusion

I am sure you must have grasped a lot about Python’s excellent exception handling. And you have understood that Exception handling is an essential tool for writing robust, error-resistant Python programs. By understanding how to use try, except, else, finally, and custom exceptions, you can gracefully manage errors, ensuring that your programs can handle unexpected situations and continue to run smoothly. Python’s wide range of built-in exceptions, along with the ability to create custom ones, provides developers with the flexibility to deal with any potential issues that may arise during execution.

Curated Reads

Understanding Python Program Flow

Dhakate Rahul

Dhakate Rahul

3 thoughts on “The Python Journey – Chapter V Python Exceptions Handling

  1. Wow superb blog layout How long have you been blogging for you make blogging look easy The overall look of your site is magnificent as well as the content

  2. I’m often to blogging and i really appreciate your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.

Leave a Reply

Your email address will not be published. Required fields are marked *