{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[Python for Developers](http://ricardoduarte.github.io/python-for-developers/#content)\n", "===================================\n", "First Edition\n", "-----------------------------------\n", "\n", "Chapter 13: Exceptions\n", "=============================\n", "_____________________________\n", "When a failure occurs in the program (such as division by zero, for example) at runtime, an exception is generated. If the exception is not handled, it will be propagated through function calls to the main program module, interrupting execution." ] }, { "cell_type": "code", "collapsed": false, "input": [ "print 1/0" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "ZeroDivisionError", "evalue": "integer division or modulo by zero", "output_type": "pyerr", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mprint\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m/\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mZeroDivisionError\u001b[0m: integer division or modulo by zero" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The *try* instruction allows exception handling in Python. If an exception occurs in a block marked by *try*, it is possible to handle the exception through the instruction *except*. It is possible to have many *except* blocks for the same *try* block." ] }, { "cell_type": "code", "collapsed": false, "input": [ "try:\n", " print 1/0\n", "except ZeroDivisionError:\n", " print 'Error trying to divide by zero.'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Error trying to divide by zero.\n" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If *except* receives the name of an exception, only that exception will be handled. If no exception name is passed as a parameter, all exceptions will be handled.\n", "\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import traceback\n", "\n", "# Try to get a file name\n", "try:\n", " fn = raw_input('Nome do arquivo: ').strip()\n", "\n", " # Numbering lines\n", " for i, s in enumerate(file(fn)):\n", " print i + 1, s,\n", "\n", "# If an error happens\n", "except:\n", "\n", " # Show it on the screen\n", " trace = traceback.format_exc()\n", "\n", " # And save it on a file\n", " print 'An error happened:\\n', trace\n", " file('trace.log', 'a').write(trace)\n", "\n", " # end the program\n", " raise SystemExit" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Nome do arquivo: test\n" ] }, { "ename": "SystemExit", "evalue": "", "output_type": "pyerr", "traceback": [ "An exception has occurred, use %tb to see the full traceback.\n", "\u001b[1;31mSystemExit\u001b[0m\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "An error happened:\n", "Traceback (most recent call last):\n", " File \"\", line 8, in \n", " for i, s in enumerate(file(fn)):\n", "IOError: [Errno 2] No such file or directory: 'test'\n", "\n" ] }, { "output_type": "stream", "stream": "stderr", "text": [ "To exit: use 'exit', 'quit', or Ctrl-D.\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The module *traceback* offers functions for dealing with error messages. The function format_exc() returns the output of the last exception formatted in a *string*.\n", "\n", "The handling of exceptions may have an *else* block, which will be executed when no exception occurs and a *finally* block, which will be executed anyway, whether an exception occurred or not. New types of exceptions may be defined through inheritance of the class *Exception*.\n", "\n", "Since version 2.6, the instruction *with* is available, that may replace the combination of *try / finally* in many situations. It is possible to define an object that will be used during the *with* block execution. The object will support the context management protocol, which means that it will need to have an `__enter__()` method, which will be executed at the beginning of the block, and another called `__exit__()`, which will be called at the end of the block.\n", "\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import random\n", "\n", "# Creates a file with 25 random numbers\n", "with file('temp.txt', 'w') as temp:\n", " for y in range(5):\n", " for x in range(5):\n", " # \"print >> \" records command output on the file\n", " print >> temp, '%.2f' % random.random(),\n", " print >> temp\n", "\n", "# Shows file content\n", "with file('temp.txt') as temp:\n", " for i in temp:\n", " print i,\n", "\n", "# Out of the blocks, the file will be closed\n", "# The following command generates an exception ValueError: I/O operation on closed file\n", "print >> temp" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "I/O operation on closed file", "output_type": "pyerr", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 16\u001b[0m \u001b[1;31m# Out of the blocks, the file will be closed\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 17\u001b[0m \u001b[1;31m# This generates an exception ValueError: I/O operation on closed file\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 18\u001b[1;33m \u001b[1;32mprint\u001b[0m \u001b[1;33m>>\u001b[0m \u001b[0mtemp\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mValueError\u001b[0m: I/O operation on closed file" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "0.06 0.66 0.01 0.94 0.58\n", "0.93 0.72 0.14 0.88 0.50\n", "0.74 0.34 0.64 0.51 0.95\n", "0.35 0.87 0.10 0.02 0.21\n", "0.66 0.92 0.66 0.46 0.82\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "With file closed at the end of the block, the record attempt generates an exception.\n" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "" ], "output_type": "pyout", "prompt_number": 1, "text": [ "" ] } ], "prompt_number": 1 } ], "metadata": {} } ] }