exception handling in python

Exceptions Handling in Python | Python Institute in Delhi

Exception handling is a programming concept, important to code applications. Handling exceptions make the difference between a smoothly running program and unexpected crashes due to run-time errors. Python provides a powerful mechanism for managing exceptions. Through this, developers respond to unforeseen errors in their code Programing trainer from Python institute in Delhi explains the Exceptions handling in Python.

What are Exceptions in Python?

An exception is an event or error condition that interrupts the normal flow of program execution. Exceptions are raised when something unexpected occurs during runtime. Examples are: division by zero, an attempt to open a non-existent file or an out-of-range list index.

In Layman terms, consider exceptions as signals that alert the program when an unusual situation arises. Instead of letting the program stopping suddenly when it encounters an error,  it allows to detect exceptional events and take appropriate actions.

Need for Exception Handling

Following are the reasons why exception handling is needed:

  • It allows program to respond to errors, preventing abrupt crashes when something goes wrong. Instead of terminating abruptly, your program can catch and handle exceptions.
  • Exceptions are used for debugging. When an error occurs,  it generates an exception that contains information about the nature and location of the error.
  • Building applications requires handling unexpected situations. Exception handling ensures that program handle unforeseen errors or situations, making it more reasonable in real-world scenarios.

Common Built-in Exceptions

Python has set of built-in exceptions to address various error scenarios. Here are some frequently encountered built-in exceptions:

  • ZeroDivisionError: It occurs when you attempt to divide by zero.You can try the code on any online tool. Operatos in Python are explained in previous blogs of ESS
  • TypeError: It is raised when an operation is performed on an inappropriate data type.
  • ValueError: It is raised when a function receives an argument of the correct data type but the value is inappropriate.
  • IndexError: Raised when trying to access an index that is out of range for a sequence (e.g., a list or a string).
  • KeyError: It is raised when you attempt to access a non-existent dictionary key.
  • FileNotFoundError: This occurs when trying to open or manipulate a file that doesn’t exist.
  • ImportError: It is raised when an imported module cannot be found.

Example 1: ZeroDivisionError

exceptional handling in python

Attempting to divide a number by zero results in a ZeroDivisionError

Example 2: TypeError

TypeError in Python

Here, an attempt to add a string and an integer leads to a TypeError

Example 3: ValueError

value error in python

In this case, converting a non-numeric string to an integer results in a value error.

Example 4: IndexError

IndexError python

Accessing an index that is out of range for a list raises an IndexError.

Example 5: KeyError

KeyError in Python

Attempting to access a key that doesn’t exist in the dictionary results in a KeyError.

Example 6: FileNotFoundError

Example 6: FileNotFoundError

When trying to open a file that doesn’t exist,  it raises a FileNotFoundError.

Example 7: ImportError

import error in python

Attempting to import a module that cannot be found results in an ImportError.

Handling Exceptions in Python

Handling Exceptions in Python is done through the try and except blocks. The try block encapsulates the code that raise an exception, while the except block is designed to catch and handle the exception. Let’s look at the basic syntax:

    # Code that will raise an exception
except SomeException as e:
    # Handle the exception

Here’s how it works:

  • The code inside the try block is executed.
  • If an exception occurs within the try block, System will search for a matching except block.
  • If a matching except block is found, its code is executed to handle the exception.
  • After the except block executes, the program resumes its normal execution.

You can catch specific exceptions by specifying the exception type in the except block, enabling you to handle different types of exceptions differently:

    # Code to raise a specific exception
except SpecificException as e:
    # Handle the specific exception

For example, if attempting a division by zero:

    result = 10 / 0  # Attempt a division by zero
except ZeroDivisionError as e:
    print(f"Error: {e}")

To handle multiple types of exceptions, use multiple except blocks, with Python executing the first matching block it encounters:

    # Code to raise an exception
except SpecificException as e:
    # Handle the specific exception
except AnotherException as e:
    # Handle another specific exception

Consider this example, where we handle both ZeroDivisionError and ValueError exceptions separately:

    user_input = int(input("Enter a number: "))
    result = 10 / user_input
except ZeroDivisionError as e:
    print("Error: Cannot divide by zero")
except ValueError as e:
    print("Error: Invalid input. Please enter a valid number.")

Python introduces the else and finally clauses to enhance exception handling. The else block runs when no exception occurs within the try block, often used for code that should only run if no exceptions were raised:

    # Code to raise an exception
except SpecificException as e:
    # Handle the specific exception
    # Code to run if no exceptions occurred

The finally block is always executed, regardless of the exception raised. It’s commonly used for cleanup code, such as closing files or releasing resources:

    # Code that might raise an exception
except SpecificException as e:
    # Handle the specific exception
    # Cleanup code that always runs

Combining try, except, else, and finally, consider this example where we attempt to open a file, read its content, and close the file in the finally block:

    file = open("example.txt", "r")
except FileNotFoundError as e:
    print("Error: File not found")
    content = file.read()
    print("File content:", content)
    file.close()  # Always close the file, even if an exception occurred

When to Raise Exceptions?

Exceptions are raised when the flow of the program is disturbed due to errors or exceptional conditions occured during a run time of code. By doing so, users are notified about the exceptional situation that has occurred.

Best Practices for Exceptions Handling

Following are the best practices to be followed in any programming language for better user experience:

  1. Pinpoint exceptions for targeted error resolution, improves the code.
  2. During exception handling, make it a habit to log information for debugging purposes. Document the expected exceptions and mention error-handling strategies.
  3. Provide fallbacks to come back from exceptions, ensuring that program to handle unexpected situations.

Python exception handling helps in error elimination. This concept helps in all programming language. You can make yourself a good developer joining ESS Institute, python training institute in Delhi.

Call Now Button