Home » Posts tagged 'Python exception handling techniques'

Tag Archives: Python exception handling techniques

Newly Updated Posts

Error and Exception in Python

Python uses errors and exceptions to deal with extraordinary circumstances that could arise while a programme is being executed. The usual flow of the programme is interrupted when an error or exception occurs, and Python raises an error or exception object to specify the error’s kind and specifics. Try-except blocks can be used to handle these mistakes and exceptions. Here is an illustration of how Python handles errors and exceptions:

# Example 1: Handling a specific exception

try:
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
    print("Result:", result)
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

# Example 2: Handling multiple exceptions

try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print("Result:", result)
except ValueError:
    print("Error: Invalid input. Please enter a valid number.")
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")

# Example 3: Handling any exception (generic exception)

try:
    file = open("nonexistent_file.txt", "r")
    content = file.read()
    file.close()
    print("Content:", content)
except Exception as e:
    print("Error:", str(e))

In the first example, a ,ZeroDivisionError, exception is handled if the user enters zero as the second number for division. In the second example, both 'ValueError and ZeroDivisionError' exceptions are handled, depending on the user’s input. In the third example, a generic Exception is caught, which can handle any type of exception. The 'as' keyword allows you to access the exception object, which can be useful for printing error messages or retrieving specific information about the error.

Build-in exception in python

When certain faults or extraordinary circumstances arise during the execution of a programme, built-in exceptions in the Python programming language can be raised (or thrown). These exceptions, which are defined in the Python standard library, can be applied to deal with particular error kinds.

1.TypeError: Raised when an operation or function is applied to an object of inappropriate type.

# Example: TypeError
x = 10
y = '5'
z = x + y  # Raises TypeError: unsupported operand type(s) for +: 'int' and 'str'

2. ValueError: Raised when a function receives an argument of the correct type but an inappropriate value.

# Example: ValueError
age = input("Enter your age: ")
age = int(age)  # Raises ValueError if the input cannot be converted to an integer

3. IndexError: Raised when a sequence subscript is out of range.

# Example: IndexError
numbers = [1, 2, 3]
print(numbers[3])  # Raises IndexError: list index out of range

4. KeyError: Raised when a dictionary key is not found.

# Example: KeyError
person = {'name': 'John', 'age': 30}
print(person['gender'])  # Raises KeyError: 'gender'

5. FileNotFoundError: Raised when a file or directory is requested but cannot be found.

# Example: FileNotFoundError
file_path = 'path/to/nonexistent/file.txt'
with open(file_path, 'r') as file:  # Raises FileNotFoundError
    content = file.read()

6. ZeroDivisionError: Raised when division or modulo operation is performed with zero as the divisor.

# Example: ZeroDivisionError
x = 10
y = 0
result = x / y  # Raises ZeroDivisionError: division by zero

7. ZeroDivisionError: Raised when division or modulo operation is performed with zero as the divisor.

8. ImportError: Raised when an import statement fails to find and load a module.

9. AssertionError: Raised when an assert statement fails.

10. StopIteration: Raised to signal the end of an iterator.

These are just a few examples of built-in exceptions in Python. You can also create your own custom exceptions by deriving from the base Exception class or any other built-in exception class.

Python Try except

The try and except commands are used in Python to handle errors and exceptions. They let you to manage potential exceptions that may arise while your code is being executed, preventing your program from crashing.

The basic syntax for using try and except is as follows:

try:
    # code that might raise an exception
    # ...
except ExceptionType1:
    # code to handle the exception of type ExceptionType1
    # ...
except ExceptionType2:
    # code to handle the exception of type ExceptionType2
    # ...
else:
    # optional block executed if no exceptions were raised
    # ...
finally:
    # optional block of code that will be executed regardless of whether an exception occurred or not
    # ...

Here’s a breakdown of the different parts:

  • The try block contains the code that you want to execute, which might raise an exception.
  • If an exception of type ExceptionType1 occurs in the try block, the corresponding except block will be executed. You can have multiple except blocks to handle different types of exceptions.
  • The else block is optional and is executed if no exceptions were raised in the try block.
  • The finally block is also optional and is executed regardless of whether an exception occurred or not. It is typically used for cleanup tasks, such as closing files or releasing resources.

Here’s an example that demonstrates the usage of try and except:

try:
    x = int(input("Enter a number: "))
    result = 10 / x
    print("The result is:", result)
except ValueError:
    print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("No exceptions were raised.")
finally:
    print("This block always executes.")

In this example, if the user enters a non-numeric value, a ValueError exception will be raised, and the corresponding except block will handle it. If the user enters zero, a ZeroDivisionError exception will be raised. If the user enters a valid number, the code in the else block will be executed. Finally, the finally block will be executed regardless of the outcome.

By using try and except, you can gracefully handle exceptions and provide appropriate error messages or alternative behavior, improving the robustness of your code.