Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In the old days, when people wrote in assembly language or C, every time you called a function that might fail, you had to check whether it succeeded. So you'd have code like this:</p> <pre><code>def countlines(path): f = open(path, 'r') if not f: print("Couldn't open", path) return None total = 0 for line in f: value, success = int(line) if not success: print(line, "is not an integer") f.close() return None total += value f.close() return total </code></pre> <p>The idea behind exceptions is that you don't worry about those exceptional cases, you just write this:</p> <pre><code>def countlines(path): total = 0 with open(path, 'r') as f: for line in f: total += int(line) return total </code></pre> <p>If Python can't open the file, or turn the line into an integer, it will raise an exception, which will automatically close the file, exit your function, and quit your whole program, printing out useful debugging information.</p> <p>In some cases, you want to handle an exception instead of letting it quit your program. For example, maybe you want to print the error message and then ask the user for a different filename:</p> <pre><code>while True: path = input("Give me a path") try: print(countlines(path)) break except Exception as e: print("That one didn't work:", e) </code></pre> <p>Once you know the basic idea that exceptions are trying to accomplish, <a href="http://docs.python.org/3/tutorial/errors.html" rel="nofollow">the tutorial</a> has a lot of useful information.</p> <p>If you want more background, <a href="http://en.wikipedia.org/wiki/Exception_handling" rel="nofollow">Wikipedia</a> can help (although the article isn't very useful until you understand the basic idea).</p> <p>If you still don't understand, ask a more specific question.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload