0% found this document useful (0 votes)
318 views

Module 5 File - Exception Handling

The document discusses exception handling in Python. It provides code to open a file, handle potential errors, and explains the purpose of the 'r' prefix in file paths. It also defines try, except, else, and finally blocks used in exception handling and describes some built-in exceptions. Finally, it discusses writing custom exceptions.

Uploaded by

Gïrìsh Gowrí
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
318 views

Module 5 File - Exception Handling

The document discusses exception handling in Python. It provides code to open a file, handle potential errors, and explains the purpose of the 'r' prefix in file paths. It also defines try, except, else, and finally blocks used in exception handling and describes some built-in exceptions. Finally, it discusses writing custom exceptions.

Uploaded by

Gïrìsh Gowrí
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

MODULE – 5 ASSIGNMENT

File Handling & Exception Handling

1) Write the code in Python to open a file named “try.txt”

try:

# Open the file in read mode ('r' for reading)

with open("try.txt", "r") as file:

# Do something with the file, such as reading its contents

file_contents = file.read()

print(file_contents)

except FileNotFoundError:

print("The file 'try.txt' was not found.")

except IOError:

print("An error occurred while trying to open the file.")

2) What is the purpose of ‘r’ as a prefix in the given statement?

f = open(r, “d:\color\flower.txt”)

In the given statement:

```python

f = open(r, "d:\color\flower.txt")

```

The `r` before the file path is not being used correctly. It appears to be a typo or a
misunderstanding. In Python, the `r` character in front of a string (e.g., `r"some_string"`) is used
as a prefix to indicate a "raw string" literal. Raw string literals are used to treat backslashes (`\`)
as literal characters, rather than as escape characters.

For example, without the `r` prefix, you would need to escape backslashes in a string like this:

```python

path = "d:\\color\\flower.txt"

```

However, if you use the `r` prefix, you can write the same path like this:

```python

path = r"d:\color\flower.txt"

```

So, the purpose of `r` in this context is to tell Python that the string should be treated as a raw
string, and backslashes should not be treated as escape characters. However, in the given
statement, it seems like `r` is being used incorrectly, and you should provide the correct file
path as a string without the `r` prefix:

3) Write a note on the following

A. Purpose of Exception Handling


B. Try block
C. Except block
D. Else block
E. Finally block
F. Bulit-in exceptions
A. **Purpose of Exception Handling:**

Exception handling is a crucial concept in programming that allows you to gracefully handle
unexpected errors or exceptional situations that might occur during the execution of a
program. The main purposes of exception handling are:

- **Error Detection:** It helps identify and detect errors or exceptions in your code.

- **Error Handling:** It provides a mechanism to handle these exceptions in a controlled and


predictable manner.

- **Program Robustness:** Exception handling enhances the robustness of your program by


preventing it from crashing due to unforeseen issues.

- **Debugging:** It aids in debugging by providing information about what went wrong.

B. **Try block:**

- The `try` block is used to enclose the code that might raise an exception.

- When an exception occurs within the `try` block, the control is transferred to the nearest
matching `except` block.

C. **Except block:**

- The `except` block follows a `try` block and specifies how to handle specific exceptions.

- Multiple `except` blocks can be used to handle different types of exceptions.

- If an exception is raised in the `try` block and matches an `except` block, the code in that
`except` block is executed.

D. **Else block:**

- The `else` block is optional and can be used after `try` and `except` blocks.

- It contains code that will run only if no exceptions were raised in the preceding `try` block.

- It is often used for code that should execute when everything in the `try` block succeeds.
E. **Finally block:**

- The `finally` block is also optional and follows the `try` and `except` blocks.

- It contains code that will always be executed, whether an exception occurred or not.

- It is typically used for cleanup operations, such as closing files or network connections.

F. **Built-in exceptions:**

- Python provides a wide range of built-in exceptions that represent various error conditions.
Some common built-in exceptions include:

- `SyntaxError`: Raised when there is a syntax error in the code.

- `NameError`: Raised when a variable or name is not found.

- `TypeError`: Raised when an operation is performed on an inappropriate data type.

- `ValueError`: Raised when a function receives an argument of the correct data type but
with an inappropriate value.

- `FileNotFoundError`: Raised when trying to open or access a file that doesn't exist.

- You can also create custom exceptions by defining your own classes that inherit from the
`BaseException` class or its subclasses.

Exception handling is a fundamental aspect of writing robust and reliable code, as it allows you
to gracefully handle errors and recover from unexpected situations, improving the overall
quality and reliability of your software.

4) Write 2 Custom exceptions

InvalidEmailError:

This custom exception can be used to raise an error when an invalid email address is
encountered.
InsufficientBalanceError:

This custom exception can be used in a banking application to raise an error when an account
has insufficient balance for a transaction.

You might also like