READING-NOTE

View on GitHub

FileIO & Exceptions

Reading and Writing Files in Python

array-insert-shift

Header: metadata about the contents of the file (file name, size, type, and so on)

Data: contents of the file as written by the creator or editor

End of file (EOF): special character that indicates the end of the file

File Paths

Folder Path: the file folder location on the file system where subsequent folders are separated by a forward slash / (Unix) or backslash \ (Windows)

File Name: the actual name of the file

Extension: the end of the file path pre-pended with a period (.) used to indicate the file type

/
│
├── path/
|   │
│   ├── to/
│   │   └── cats.gif
│   │
│   └── dog_breeds.txt
|
└── animals.csv

Python Exceptions

Python Exceptions

Exceptions versus Syntax Errors

Syntax errors occur when the parser detects an incorrect statement. Observe the following example:

>>> print( 0 / 0 ))
  File "<stdin>", line 1
    print( 0 / 0 ))
                  ^
SyntaxError: invalid syntax

The arrow indicates where the parser ran into the syntax error. In this example, there was one bracket too many. Remove it and run your code again:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

Raising an Exception

We can use raise to throw an exception if a condition occurs. The statement can be complemented with a custom exception.

Raising an Exception

If you want to throw an error when a certain condition occurs using raise, you could go about it like this:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))

When you run this code, the output will be the following:

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10

The AssertionError Exception

The try and except Block: Handling Exceptions

The else Clause

Cleaning Up After Using finally

Summing Up

  1. raise allows you to throw an exception at any time.
  2. assert enables you to verify if a certain condition is met and throw an exception if it isn’t.
  3. In the try clause, all statements are executed until an exception is encountered.
  4. except is used to catch and handle the exception(s) that are encountered in the try clause.
  5. else lets you code sections that should run only when no exceptions are encountered in the try clause.
  6. finally enables you to execute sections of code that should always run, with or without any previously encountered exceptions.