Error Handling and Exceptions in Python

In Python, handling errors and exceptions is an essential part of the programming process. When running a program, unexpected errors and exceptions may occur. Handling errors and exceptions allows the program to handle and report these unexpected situations flexibly and in a readable manner.

 

Handling Common Errors (Exception Handling)

In Python, we use the try-except block to handle common errors. The try-except structure allows the program to execute a block of code in the try section, and if an error occurs in this block, the program will move to the except section to handle that error.

Example:

try:
    # Attempt to perform an invalid division
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")

 

Handling General Exceptions

In addition to handling specific types of errors, we can also use except without specifying a specific error type. This helps handle general exceptions that we do not know in advance.

Example:

try:
    # Attempt to perform an invalid division
    result = 10 / 0
except:
    print("An error occurred.")

 

Handling Multiple Exception Types

We can also handle multiple different types of errors in the same try-except block by using multiple except clauses.

Example:

try:
    # Attempt to open a non-existent file
    file = open("myfile.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("Error: File not found.")
except PermissionError:
    print("Error: No permission to access the file.")

 

The else and finally Clauses

  • The else clause allows executing a block of code when there is no error in the try section.
  • The finally clause allows executing a block of code after both the try and except sections are completed.

Example:

try:
    num = int(input("Enter an integer: "))
except ValueError:
    print("Error: Not an integer.")
else:
    print("The number you entered is:", num)
finally:
    print("Program ends.")

 

Handling errors and exceptions in Python makes the program more robust and increases its stability. When handling errors properly, we can provide appropriate messages or perform actions accordingly when unexpected situations occur.