fbpx

Understanding Python Exception Types and How to Handle Them

Understanding Python Exception Types and How to Handle Them

INTRODUCTION

Exception handling is an essential part of writing robust Python code, as it helps programs manage errors gracefully rather than abruptly terminating. In this guide, we’ll explore the common types of exceptions in Python, such as SyntaxError, TypeError, IndexError, and ZeroDivisionError, among others, and provide examples of how each occurs in real-world scenarios.

We’ll also delve into the try and except blocks, which allow you to catch specific exceptions and handle them accordingly. Using these blocks ensures that your code can respond appropriately to a variety of runtime issues, such as invalid input or unavailable resources, without crashing. The finally block is another useful tool in exception handling, allowing you to perform cleanup tasks, like closing files or releasing resources, regardless of whether an error occurred.

  • SyntaxError:

If there is syntax error in the code  such as missing parenthesis,misspelt word.

Example1:

if x == 10

    print(“x is 10”)

# Output: SyntaxError: invalid syntax

  • TypeError:This occurs when incompatible data types are added

Example2:

#incompatible datatypes are added

parabola=10;

Str=”thenmozhi”

Print(parabola+str) // x and integer and str is an str incompatible  datatypes

  • NameError: Occurs when a variable or function name isn’t found within the current scope.

Example 3:

 

print(value)# Here we are using the variable before  it has been defined.

# Output: NameError: name ‘value’ is not defined

  • Indexerror:( out of range elements)

Example 4:

 

numbers = [1, 2, 3] #here the idexes are 0 1,2 we are trying to access 5 index

print(numbers[5])

# IndexError: list index out of range

KeyError: ( accessing the invalid key in the dictionary)

Example 5:

my_dict = {“a”: 1, “b”: 2}

print(my_dict[“c”])

# Output: KeyError: ‘c’

  • ValueError: Occurs when a function or method receives an argument of the right type but an invalid value, such as attempting to convert an invalid string to an integer.

Example 6:

int_value = int(“hello”)

# Output: ValueError: invalid literal for int() with base 10: ‘hello’

 

  • AttributeError: Triggered when a requested attribute or method is not found on an object, like accessing a nonexistent attribute in a class instance.

Example 7:

# Trying to access a nonexistent attribute

class Sample:

    pass

obj = Sample()

obj.attribute

# Output: AttributeError: ‘Sample’ object has no attribute ‘attribute’

  • IOError:This error occurred when input/output actions into a file.when file not found.

Example:

# Trying to open a nonexistent file

with open(“nonexistent_file.txt”, “r”) as file:

    content = file.read()

# Output: IOError (or FileNotFoundError in Python 3): [Errno 2] No such file or directory: ‘nonexistent_file.txt’

  • ZeroDivisionError: (number divide by 0)

Example:

# Attempting to divide by zero

result = 10 / 0

# Output: ZeroDivisionError: division by zero

  • ImportError: occurs when the import fails to load and locate.

# Trying to import a nonexistent module

import nonexistent_module

# Output: ImportError: No module named ‘nonexistent_module’

DIFFERENCE BETWEEN SYNTAX ERRROR AND EXCEPTION

—————————————————————————–

Syntax error: syntax error are arised due to  any  syntax error in the program.

Exception : it the case Exception it says that where the program is  syntactically  correct  but code results in error is  called  Exception

mark = 2000

a = mark / 0

print(a)

 

try and except block:

 In this block  the program is to run smoothly eventhrough the error occurs

try:

   

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

    result = 100 / number

    print(f”Result: {result}”)

 

except ValueError:

    # This block runs if there’s a ValueError (e.g., if input isn’t a number)

    print(“Please enter a valid integer.”)

 

except ZeroDivisionError:

    # This block runs if there’s a ZeroDivisionError (e.g., if the number is zero)

    print(“Cannot divide by zero.”)

 

except Exception as e:

    # This block runs for any other exceptions

    print(f”An unexpected error occurred: {e}”)

 

finally:

    # This block always runs, even if there’s an error

    print(“Execution completed.”)

 

Catching Specific Exception

In Python, catching specific exceptions allows you to handle different error types individually and take appropriate action for each.

This improves error handling and gives more precise control over what happens when specific errors occur.

try:

    numbers = [1, 2, 3]

    index = int(input())

    divisor = int(input())

   

    result = 100 / divisor

    print(f”Result: {result}”)

   

    print(f”Number at index {index}: {numbers[index]}”)

 

except IndexError:

    print(“Index out of range! Please enter a valid index.”)

 

except ZeroDivisionError:

    # This block handles attempts to divide by zero

    print(“Cannot divide by zero.”)

 

except ValueError:

    print(“Invalid input! Please enter an integer.”)

 

except Exception as e:

    # This catches any other unforeseen exceptions

    print(f”An unexpected error occurred: {e}”)

 

finally:

    print(“Execution completed.”)

 

TRY WITH FINALLY

Finally block always  executed.

.

try:

    print(“Trying to divide by zero.”)

    result = 10 / 0

except ValueError:

    print(“A ValueError occurred.”)

finally:

    print(“This will always execute.”)

 

  • The ZeroDivisionError isn’t caught because there’s no matching except for it, so the program will terminate after running finally.

Use finally for actions you need to perform no matter what happens in the try block, such as:

  • Closing files or network connections.
  • Releasing resources (e.g., database connections).
  • Resetting certain states.

Advantages of Exception handling

1. Error Management
2.Improved Program Flow
3. Simplified Error Detection and Debugging
4. Code Separation and Modularity
5. Resource Management
6. Enhanced Code Reliability and Resilience
7. Custom Error Messages

 

Disadvantages of Exception handling:

Exception handling is a powerful feature in programming, but it also has some disadvantages. Here are a few key disadvantages to consider:

1. Performance Overhead
2. Complexity and Readability
3. Unintentional Suppression of Errors
4. Potential for Resource Leaks
5. Difficulty in Debugging