Errors and Files
When something goes wrong, Python raises an exception. Catch it with try / except so your program keeps running. finally always runs.
Things go wrong in real programs all the time: a user types letters instead of a number, a file is missing, the internet is down. Without handling, Python stops and shows an error message - your program crashes. With try / except, you expect the problem and decide what to do: show a friendly message, use a default, or try again.
Put only the risky line(s) in try. In except, name the exact error you expect (ValueError, ZeroDivisionError...). Catching every possible error with a bare except: hides real bugs, so avoid it.
Raising your own errors
You can also raise errors yourself. This is how a function says "I can't work with this value". It's better than quietly returning a wrong answer, because the caller is forced to notice and handle the problem.
Reading and writing files
Use with open(...). It closes the file for you automatically, even if an error happens.
Files let your program remember things after it stops - saved orders, settings, reports. Variables disappear when the program ends; files stay on the disk. The with block opens the file, lets you work with it, and always closes it at the end, even if an error happens in between.
"r" read (the default), "w" write (replaces the file), "a" add to the end.try/excepthandles errors so the program doesn't crash.- Catch specific errors like
ValueError; avoid a bareexcept. raisereports a problem from your own code.- Use
with open(...)for files; modes are "r", "w" and "a".
