# File IO with Exception Handling

```python
try:
	with open('/File/Location/File_name.txt', mode='r') as my_file:
		print(my_file.read())

except:
	print("File does not exist: FileNotFoundError")
	
print('This line was run...')
```

## You can also have specific cases:

```python
try:
	with open('/File/Location/File_name.txt', mode='r') as my_file:
		print(my_file.read())

except TypeError:
	print("There was a type error")
	
except FileNotFoundError:
	print("File does not exist: FileNotFoundError")

except:
	print("Different types of error from the predicted ones")
	
print('This line was run...')
```

* The `except` clause will run only if there is a `TypeError` (Which is an object)

## There is also an additional clause called `finally`

```python
try:
	with open('/File/Location/File_name.txt', mode='r') as my_file:
		print(my_file.read())

except:
	print("There was an error")
	
finally:
	print('THIS WILL ALWAYS RUN')
```

* `finally` is a clause that will always run, no matter what

## If you are dealing with files there are sometimes errors that variables are not accessible

* In that case you would implement this in another `try` block
  * This can get confusing though so be careful

```python
try:
	my_file = open(file_name, mode='r')
	try:
		print(my_file.read())
	except IOError:
		print("There was an error")
	finally:
		my_file.close()
		print('The file was closed')
except:
	print('There was another error')
```

* `IOError` is a type where it handles all the file issues, such as:
  * No permission
  * Was not accessible
  * Does not have write permissions
  * Does not exist
  * Any issue with working with the file


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.arkannis.net/programming/courses/python-pcap-31-03-course/file-io-and-exception-handling/file-io-with-exception-handling.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
