Exceptions & Files

Ace your homework & exams now with Quizwiz!

Sort of like the case statement

A try statement can have multiple different except blocks to handle different exceptions. Multiple exceptions can also be put into a single except block using parentheses, to have the except block handle all of them. try: variable = 10 print(variable + "hello") print(variable / 2) except ZeroDivisionError: print("Divided by zero") except (ValueError, TypeError): print("Error occurred") >>> Error occurred >>>

Working with files and naming them easily.

An alternative way of doing this is using with statements. This creates a temporary variable (often called f), which is only accessible in the indented block of the with statement. with open("filename.txt") as f: print(f.read()) The file is automatically closed at the end of the with statement, even if exceptions occur within it.

Assertions

An assertion is a sanity-check that you can turn on or turn off when you have finished testing the program. An expression is tested, and if the result comes up false, an exception is raised. Assertions are carried out through use of the assert statement. print(1) assert 2 + 2 == 4 print(2) assert 1 + 1 == 3 print(3) --------------------------- Result: >>> 1 2 AssertionError >>> Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.

Except statement without exception

An except statement without any exception specified will catch all errors. These should be used sparingly, as they can catch unexpected errors and hide programming mistakes. try: word = "spam" print(word / 0) except: print("An error occurred") Result: >>> An error occurred >>> Exception handling is particularly useful when dealing with user input.

finally 2

Code in a finally statement even runs if an uncaught exception occurs in one of the preceding blocks. try: print(1) print(10 / 0) except ZeroDivisionError: print(unknown_var) finally: print("This is executed last") Result: >>> 1 This is executed last ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: NameError: name 'unknown_var' is not defined >>> Another Example try: print(1) print(10 / 0) except ZeroDivisionError: print("hello") finally: print("This is executed last") Result 1 hello This is executed last

Opening them using exceptions so it closes the file in the end

It is good practice to avoid wasting resources by making sure that files are always closed after they have been used. One way of doing this is to use try and finally. try: f = open("filename.txt") print(f.read()) finally: f.close()

Different Exceptions

Different exceptions are raised for different reasons. Common exceptions: ImportError: an import fails; IndexError: a list is indexed with an out-of-range number; NameError: an unknown variable is used; SyntaxError: the code can't be parsed properly; TypeError: a function is called on a value of an inappropriate type; ValueError: a function is called on a value of the correct type, but with an inappropriate value.

Raising Exceptions 2

Exceptions can be raised with arguments that give detail about them. For example: name = "123" raise NameError("Invalid name!") >>> NameError: Invalid name! >>>

Raising Exceptions 3

In except blocks, the raise statement can be used without arguments to re-raise whatever exception occurred. For example: try: num = 5 / 0 except: print("An error occurred") raise Result: >>> An error occurred ZeroDivisionError: division by zero >>>

Opening Files and closing them

Once a file has been opened and used, you should close it. This is done with the close method of the file object. file = open("filename.txt", "w") # do stuff to the file file.close()

Assertions Taking Argument

The assert can take a second argument that is passed to the AssertionError raised if the assertion fails. temp = -10 assert (temp >= 0), "Colder than absolute zero!" Result: >>> AssertionError: Colder than absolute zero! >>>

Writing Files and returning the number of bytes written to a file

The write method returns the number of bytes written to a file, if successful. msg = "Hello world!" file = open("newfile.txt", "w") amount_written = file.write(msg) print(amount_written) file.close() Result: >>> 12 >>>

Exceptions

They occur when something goes wrong, due to incorrect code or input. When an exception occurs, the program immediately stops. The following code produces the ZeroDivisionError exception by trying to divide 7 by 0.

Use of finally

To ensure some code runs no matter what errors occur, you can use a finally statement. The finally statement is placed at the bottom of a try/except statement. Code within a finally statement always runs after execution of the code in the try, and possibly in the except, blocks. try: print("Hello") print(1 / 0) except ZeroDivisionError: print("Divided by zero") finally: print("This code will run no matter what") Result: >>> Hello Divided by zero This code will run no matter what >>>

Exception Handling

To handle exceptions, and to call code when an exception occurs, you can use a try/except statement. The try block contains code that might throw an exception. If that exception occurs, the code in the try block stops being executed, and the code in the except block is run. If no error occurs, the code in the except block doesn't run.

Writing Files

To write to files you use the write method, which writes a string to the file. For example: file = open("newfile.txt", "w") file.write("This has been written to a file") file.close() file = open("newfile.txt", "r") print(file.read()) file.close() Result: >>> This has been written to a file >>>

Writing Files and contents being deleted

When a file is opened in write mode, the file's existing content is deleted. file = open("newfile.txt", "r") print("Reading initial contents") print(file.read()) print("Finished") file.close() file = open("newfile.txt", "w") file.write("Some new text") file.close() file = open("newfile.txt", "r") print("Reading new contents") print(file.read()) print("Finished") file.close() Result: >>> Reading initial contents some initial text Finished Reading new contents Some new text Finished >>> Kinda Harder to see this but, every time you open the file, the data gets deleted.w

Raising Exceptions

You can raise exceptions by using the raise statement. print(1) raise ValueError print(2) Result: >>> 1 ValueError >>> You need to specify the type of the exception raised.

Opening Files by applying a second argument

You can specify the mode used to open a file by applying a second argument to the open function. Sending "r" means open in read mode, which is the default. Sending "w" means write mode, for rewriting the contents of a file. Sending "a" means append mode, for adding new content to the end of the file. Adding "b" to a mode opens it in binary mode, which is used for non-text files (such as image and sound files). For example: # write mode open("filename.txt", "w") # read mode open("filename.txt", "r") open("filename.txt") # binary write mode open("filename.txt", "wb") You can use the + sign with each of the modes above to give them extra access to files. For example, r+ opens the file for both reading and writing.

Opening Files

You can use Python to read and write the contents of files. Text files are the easiest to manipulate. Before a file can be edited, it must be opened, using the open function. myfile = open("filename.txt") The argument of the open function is the path to the file. If the file is in the current working directory of the program, you can specify only its name.

An example

meaning = 42 print(meaning / 0) print("the meaning of life") except (ValueError, TypeError): print("ValueError or TypeError occurred") except ZeroDivisionError: print("Divided by zero") Output=Divided by zero

Quick exception

try, except, finally, raise


Related study sets

Assignment 9: Health Insurance Exchanges

View Set

The Corporation and its stakeholders/Managing Public Issues and Stakeholder Relationshipa

View Set

Behavioral Observation and Screening

View Set

Social Media: Our Connected World Unit 4 LinkedIn, Blogs, and Video Social Media

View Set

Chapter 20, Health History and Physical Assessment

View Set

Life Insurance policy Riders, Provisions, Options, and Exclusions.

View Set