Python Exception Handling

By Bipin Kumar Last updated : November 27, 2023

What is Python Exception?

An exception is a Python object that represents error that occurs during the execution of the program and this disturbs the flow of a program. In general, if Python does not encounter any scripts or lines of code then it raises a type of exception.

Different Types of Python Exceptions

Some of the most common built-in exceptions in Python are,

  1. ValueError:
    This type of error occurs when we have written an argument or line of code that has the right type but inappropriate value. For example, a variable is assigned with the string and we are trying to convert it into integer then we will get this type of error.
  2. ZeroDivisionError:
    This is the most common type of error which occurs when we are trying to divide or taking modulo of any integer by the Zero. For example, a variable x by 5 and we are trying to do operation x%0 or x/0 then this shows us ZeroDivisionError.
  3. ImportError:
    This error occurs when we are trying to import a module in the program but it not found. For example, if we are importing a module like Bipin in the program then it shows this type of error.
  4. IndentionError:
    As we all know that the Python follows the rule of indentation. So, when we are going to write something out of indentation then this type of error will occur.
  5. SyntaxError:
    This error occurs when we have written any incorrect syntax in the program. As we all know that the keyword 'int' is used to convert the input into an integer type but when we are trying to use 'Int' instead of 'int' then it will show the SyntaxError.
  6. IndexError:
    This type of error occurs when you are trying to access any value which is out of the given range. For example, we have created a list of lengths of 5 but we are trying to access the element at index 6 then it will show the IndexError.
  7. MemoryError:
    This type of error occurs when an operation runs out of memory.

The try except Statement

To overcome these types of exceptions in Python, we use the try-except statements.

The basic syntax of try-except statement is,

try:
   #statement
except typeofError:
   #statement

Algorithm

Algorithm of try-except statement -

  • If the code or statement provided in the try block has no exception then only try blocks will be executed.
  • If any exception occurs in the block of try then try block skipped and except block will be executed.

Python Exception Handling Examples


Example 1: Handling ZeroDivisionError

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed!")

Output:

Division by zero is not allowed!

Example 2: Handling IndexError

try:
    my_list = [10, 20, 30]
    print(my_list[3])
except IndexError:
    print("Index out of range!")

Output:

Index out of range!

Example 3: Handling ValueError

try:
    num = int("Hello")
except ValueError:
    print("Invalid value for conversion to int!")

Output:

Invalid value for conversion to int!

Example 4: Handling TypeError

try:
    sum = 15 + "20"
except TypeError:
    print("Unsupported operand type for +")

Output:

Unsupported operand type for +

Example 5: Handling FileNotFoundError

try:
    with open('anyfile.txt', 'r') as file:
        result = file.read()
except FileNotFoundError:
    print("File not found!")

Output:

File not found!

Example 6: Using else block in exception handling

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Division by zero is not allowed!")
else:
    print("Result:", result)

Output:

Result: 5.0

Example 7: Using finally block in exception handling

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed!")
finally:
    print("This block always gets executed")

Output:

Division by zero is not allowed!
This block always gets executed

Example 8: Raising custom exceptions

def divide_numbers(x, y):
    if y == 0:
        raise ValueError("Cannot divide by zero")
    return x / y

Output:

RUN 1: If calling statement is print(divide_numbers(10, 0))
    raise ValueError("Cannot divide by zero")
ValueError: Cannot divide by zero

RUN 2: If calling statement is print(divide_numbers(10, 2))
5.0

Example 9: Handling multiple exceptions

try:
    age = int(input("Enter your age: "))
    if age < 0:
        raise ValueError("Age cannot be negative")
except ValueError as ve:
    print(ve)
except TypeError as te:
    print(te)

Output:

Enter your age: -8
Age cannot be negative

Example 10: Handling multiple exceptions with else block

try:
  age = int(input("Enter your age: "))
  if age < 0:
    raise ValueError("Age cannot be negative")
except ValueError as ve:
  print(ve)
except TypeError as te:
  print(te)
else:
  print("No exceptions were raised")

Output:

RUN 1:
Enter your age: -21
Age cannot be negative

RUN 2:
Enter your age: One
invalid literal for int() with base 10: 'One'

RUN 3:
Enter your age: 21
No exceptions were raised


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.