Книга: Practical Programming, Fourth Edition
Назад: Exceptionally Important!
Дальше: Bibliography

Exercises

Here are some exercises for you to try on your own.

  1. Write a program that attempts to open a file specified by the user and read its contents. Handle the cases where the file does not exist, is unreadable, or is empty. Print an informative message for each condition.

  2. Write a program that reads data from a file and writes it to another file. Use a finally block to ensure that both files are closed, even if an exception is raised while reading or writing.

  3. Write a function that reads a file and parses its contents as an integer number. Catch FileNotFoundError and re-raise a custom DataReadError from it. Then catch ValueError (invalid integer) and re-raise a DataFormatError from it. Print the original causes using the __cause__ attribute.

  4. Write a small program with three functions that call one another and deliberately raise an exception in the deepest one. Run it without handling the exception to examine the traceback. Then catch the exception and print its __traceback__ manually to see the call stack details.

  5. Deliberately write a program with an except block without a specified exception type that hides a bug. Then rewrite it to catch specific exceptions and explain how that change makes debugging easier.

  6. Write a program that tries to convert user input into an integer and then divides 100 by that number. Handle ValueError (invalid input) and ZeroDivisionError (division by zero) with different messages. Use an else block to display the result if no exceptions occur.

Назад: Exceptionally Important!
Дальше: Bibliography