Exception Handling Using Python

5
(3)

1. What is an Exception?

In Python, an exception is a runtime error that occurs when a statement or expression is syntactically correct, but the code cannot be executed properly. Exceptions are raised when there is an error in the program.

2. Types of Exceptions:

Python has a variety of built-in exceptions. Some common ones include:

  • SyntaxError: Raised when there is a syntax error in the code.
  • TypeError: Raised when an operation or function is applied to an object of an inappropriate type.
  • ValueError: Raised when a built-in operation or function receives an argument of the correct type but an inappropriate value.
  • ZeroDivisionError: Raised when division or modulo by zero occurs.
  • FileNotFoundError: Raised when a file or directory is requested but cannot be found.
  • Exception: A base class for all exceptions.

3. Try-Except Block:

To handle exceptions, you use a try-except block. The code inside the try block is executed, and if an exception occurs, the corresponding except block is executed.

try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to handle the specific exception
print(“Error: Division by zero”)

4. Handling Multiple Exceptions:

You can handle multiple exceptions by providing multiple except blocks.

try:
# Code that might raise an exception
result = int(“abc”)
except ValueError:
# Code to handle a ValueError
print(“Error: Invalid conversion to int”)
except ZeroDivisionError:
# Code to handle a ZeroDivisionError
print(“Error: Division by zero”)
except Exception as e:
# Code to handle other exceptions
print(f”An unexpected error occurred: {e}”)

5. The else and finally Blocks:

  • The else block is executed if the code in the try block does not raise an exception.
  • The finally block is always executed, whether an exception occurred or not.

try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError:
print(“Error: Division by zero”)
else:
print(f”Result: {result}”)
finally:
print(“This block always runs”)

6. Raising Exceptions:

You can manually raise exceptions using the raise statement.

def example_function(value):
if value < 0:
raise ValueError(“Value must be non-negative”)
return value

try:
result = example_function(-5)
except ValueError as e:
print(f”Error: {e}”)

7. Custom Exceptions:

You can create custom exceptions by defining new classes that inherit from the Exception class.

class CustomError(Exception):
def init(self, message):
self.message = message

try:
raise CustomError(“This is a custom error”)
except CustomError as ce:
print(f”Custom error caught: {ce.message}”)

Handling file operations in Python:

Handling file operations in Python involves opening, reading, writing, and closing files. Additionally, it’s crucial to handle exceptions that might occur during these operations. Here’s a guide on handling file operations in Python:

Reading from a File:

try:
with open(‘example.txt’, ‘r’) as file:
content = file.read()
print(content)
except FileNotFoundError:
print(“The file does not exist.”)
except Exception as e:
print(f”An error occurred: {e}”)

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 3

No votes so far! Be the first to rate this post.

Be the first to comment

Leave a Reply

Your email address will not be published.


*