12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

def gosouth(x):print gobad(x, 0)gosouth(1)Because the program ignores the exception it triggers, <strong>Python</strong> kills the program, andprints a message: *% python bad.pyTraceback (most recent call last):File "bad.py", line 7, in gosouth(1)File "bad.py", line 5, in gosouthprint gobad(x, 0)File "bad.py", line 2, in gobadreturn x / yZeroDivisionError: integer division or modulo by zeroThe message consists of a stack trace and the name of (and any extra data about) theexception that was raised. The stack trace lists all lines active when the exceptionoccurred, from oldest to newest. Note that because we’re not working at the interactiveprompt, in this case, the file and line number information is useful. For example,here we can see that the bad divide happens at the last entry in the trace—line 2 of thefile bad.py, a return statement.Because <strong>Python</strong> detects and reports all errors at runtime by raising exceptions, exceptionsare intimately bound up with the ideas of error handling and debugging ingeneral. If you’ve worked through this book’s examples, you’ve undoubtedly seen anexception or two along the way—even typos usually generate a SyntaxError or otherexception when a file is imported or executed (that’s when the compiler is run). Bydefault, you get a useful error display like the one above, which helps you trackdown the problem.Often, this standard error message is all you need to resolve problems in your code.For more heavy-duty debugging jobs, you can catch exceptions with try statements,or use debugging tools I’ll introduce in Chapter 29, such as the pdb standard librarymodule.Example: Catching Built-in Exceptions<strong>Python</strong>’s default exception handling is often exactly what you want—especially forcode in a top-level script file, an error generally should terminate your programimmediately. For many programs, there is no need to be more specific about errorsin your code.* The text of error messages and stack traces tends to vary slightly over time. Don’t be alarmed if your errormessages don’t exactly match mine. When I ran this example in <strong>Python</strong> 2.5’s IDLE, for instance, its errormessage text showed the full directory paths in filenames.586 | Chapter 27: Exception Basics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!