summaryrefslogtreecommitdiff
path: root/C++_from_the_Ground/Chapter_17(1).ipynb
blob: 8694627cbfb157d39cb33638abf63a158bb47202 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
{
 "metadata": {
  "name": "Chapter 17"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h1>Chapter 17: Exception Handling<h1>"
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.1, Page Number: 397<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''A simple exception handling example'''\n\nprint \"start\"\n\ntry:                                          #start a try block\n    print \"Inside try block\"\n    raise Exception(99)                       #raise an error\n    print \"This will not execute\"\nexcept Exception,i:                           #catch an error\n    print \"Caught an exception -- value is:\",\n    print i\n\nprint \"end\"",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "start\nInside try block\nCaught an exception -- value is: 99\nend\n"
      }
     ],
     "prompt_number": 1
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.2, Page Number: 399<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "\n'''A simple exception handling example'''\n\nimport sys\n\n\n\ndef main():\n    print \"start\"\n    try:                                          #start a try block\n        print \"Inside try block\"\n        raise Exception(99)                       #raise an error\n        print \"This will not execute\"\n    except Exception,i:                           #catch an error\n        if isinstance(i,float):\n            print \"Caught an exception -- value is:\",\n            print i\n        else:\n            print \"Abnormal program termination\"\n            return\n    print \"end\"\n\n    \nmain()",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "start\nInside try block\nAbnormal program termination\n"
      }
     ],
     "prompt_number": 1
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.3, Page Number: 400<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Throwing an exception from a function called \n   from within a try block'''\n\ndef Xtest(test):\n    print \"Inside Xtest, test is: \",test\n    if(test):\n        raise Exception(test)\n        \nprint \"start\"\n\ntry:                         #start a try block\n    print \"Inside try block\"\n    Xtest(0)\n    Xtest(1)\n    Xtest(2)\nexcept Exception,i:          #catch an error\n    print \"Caught an exception -- value is:\",\n    print i\n\nprint \"end\"",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "start\nInside try block\nInside Xtest, test is:  0\nInside Xtest, test is:  1\nCaught an exception -- value is: 1\nend\n"
      }
     ],
     "prompt_number": 2
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.4, Page Number: 401<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''A try/except is reset each time a function is entered'''\n\ndef Xhandler(test):\n    try:\n        if(test):\n            raise Exception(test)\n    except Exception,i:\n        print \"Caught One! Ex #:\",i\n        \nprint \"start\"\n\nXhandler(1)\nXhandler(2)\nXhandler(0)\nXhandler(3)\n\nprint \"end\"",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "start\nCaught One! Ex #: 1\nCaught One! Ex #: 2\nCaught One! Ex #: 3\nend\n"
      }
     ],
     "prompt_number": 3
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.5, Page Number: 401<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Use exception class'''\n\nclass MyException:\n    def __init__(self,s):\n        self.str_what=s\n        \n#Variable declaration\na=None \nb=None\n\ntry:\n    print \"Enter numerator and denominator:\"\n    #User-input\n    a=10                                     \n    b=0\n    if not(b):\n        raise MyException(\"Cannot divide by zero!\")\n    else:\n        print \"Quotient is\",a/b\nexcept MyException as e:        #catch an error\n    print e.str_what\n    ",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Enter numerator and denominator:\nCannot divide by zero!\n"
      }
     ],
     "prompt_number": 4
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.6, Page Number: 403<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Different types of exceptions being caught'''\n\nclass MyException:\n    def __init__(self,s):\n        self.x=s\n        \ndef Xhandler(test):\n    try:\n        if(test):\n            raise MyException(test)\n        else:\n            raise MyException(\"Value is zero\")\n    except MyException as i:\n        if isinstance(i.x,int):\n            print \"Caught One! Ex #:\",i.x\n        else:\n            print \"Caught a string:\",\n            print i.x\n        \nprint \"start\"\n\nXhandler(1)\nXhandler(2)\nXhandler(0)\nXhandler(3)\n\nprint \"end\"",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "start\nCaught One! Ex #: 1\nCaught One! Ex #: 2\nCaught a string: Value is zero\nCaught One! Ex #: 3\nend\n"
      }
     ],
     "prompt_number": 5
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.7, Page Number: 404<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Catching derived classes'''\n\nclass B:\n    pass\n\nclass D(B):\n    pass\n\nderived=D()\n\ntry:\n    raise B()\nexcept B as b:\n    print \"Caught a base class.\"\nexcept D as d:\n    print \"This wont execute.\"\n    ",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Caught a base class.\n"
      }
     ],
     "prompt_number": 6
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.8, Page Number: 405<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Example to catch all exceptions'''\n\ndef Xhandler(test):\n    try:\n        if test==0:\n            raise Exception(test)       #throw int\n        if test==1:\n            raise Exception('a')        #throw char\n        if test==2:\n            raise Exception(123.23)     #throw double\n    except:                             #Catches all exceptions\n        print \"Caught One!\"\n\nprint \"start\"\n\nXhandler(0)\nXhandler(1)\nXhandler(2)\n\nprint \"end\"",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "start\nCaught One!\nCaught One!\nCaught One!\nend\n"
      }
     ],
     "prompt_number": 7
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.9, Page Number: 405<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Example to catch all exceptions'''\n\nclass MyException:\n    def __init__(self,s):\n        self.x=s\n        \ndef Xhandler(test):\n    try:\n        if test==0:\n            raise MyException(test)       #throw int\n        if test==1:\n            raise MyException('a')        #throw char\n        if test==2:\n            raise MyException(123.23)     #throw double\n    except MyException as i:\n        if isinstance(i.x,int):           #catch an int exception\n            print \"Caught\",i.x              \n        else:                             #catch all other exceptions\n            print \"Caught One!\"\n        \n\nprint \"start\"\n\nXhandler(0)\nXhandler(1)\nXhandler(2)\n\nprint \"end\"",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "start\nCaught 0\nCaught One!\nCaught One!\nend\n"
      }
     ],
     "prompt_number": 8
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.10, Page Number: 407<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Restricting function throw types'''\n\nclass MyException:\n    def __init__(self,s):\n        self.x=s\n \n#This function can only throw ints, chars and doubles\ndef Xhandler(test):\n    if test==0:\n        raise MyException(test)       #throw int\n    if test==1:\n        raise MyException('a')        #throw char\n    if test==2:\n        raise MyException(123.23)     #throw double\n     \n\nprint \"start\"\ntry:\n    Xhandler(0)\nexcept MyException as i:\n    if isinstance(i.x,int):           #catch an int exception\n        print \"Caught int\"                  \n    elif isinstance(i.x,str):        #catch a char exception\n        print \"Caught char\"\n    elif isinstance(i.x,float):       #catch a float exception\n        print \"Caught double\"\n\nprint \"end\"",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "start\nCaught int\nend\n"
      }
     ],
     "prompt_number": 9
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.11, Page Number: 408<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Example of \"rethrowing\" an exception'''\n\ndef Xhandler():\n    try:\n        raise Exception(\"hello\")  #throw a char *\n    except Exception,c:           #catch a char *\n        print \"Caugh char * inside Xhandler\"\n        raise                     #rethrow char * out of function\n        \nprint \"start\"\ntry:\n    Xhandler()\nexcept Exception,c:\n    print \"Caught char * inside main\"\n    \nprint \"end\"",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "start\nCaugh char * inside Xhandler\nCaught char * inside main\nend\n"
      }
     ],
     "prompt_number": 10
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.12, Page Number: 410<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Handle exceptions due to allocation failure'''\n\nfrom ctypes import *\n\n#Variable declaration\np=[]\n\ntry:\n    for i in range(32):\n        p.append(c_int())\nexcept MemoryError,m:\n    print \"Allocation failure.\"\n        \nfor i in range(32):\n    p[i]=i\n    \nfor i in range(32):\n    print p[i],\n    \n    ",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31\n"
      }
     ],
     "prompt_number": 12
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.13, Page Number: 410<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Checking allocation failure without raising an exception'''\n\nfrom ctypes import *\n\n#Variable declaration\np=[]\n\n\nfor i in range(32):\n    p.append(c_int())    \nif not(p):\n    print \"Allocation failure.\"\n        \nfor i in range(32):\n    p[i]=i\n    \nfor i in range(32):\n    print p[i],\n    \n    ",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31\n"
      }
     ],
     "prompt_number": 13
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": "<h3>Example 17.13, Page Number: 412<h3>"
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "'''Demonstrate overloaded new and delete'''\n\nclass three_d:\n    def __init__(self,i=0,j=0,k=0):    #3=D coordinates\n        if(i==0 and j==0 and k==0):\n            self.x=self.y=self.z=0\n            print \"Constructing 0, 0, 0\"\n        else:\n            self.x=i\n            self.y=j\n            self.z=k\n            print \"Constructing\",i,\",\",j,\",\",k\n    def __del__(self):\n        print \"Destructing\"\n    #new overloaded relative to three_d.\n    def __new__(typ, *args, **kwargs):\n        obj = object.__new__(typ, *args, **kwargs)\n        return obj\n    def show(self):\n        print self.x,\",\",\n        print self.y,\",\",\n        print self.z\n    \np1=[]*3\np2=[]\n        \ntry:\n    print \"Allocating array of three_d objects.\"\n    for i in range(3):                           #allocate array\n        p1.append(three_d())\n    print \"Allocating three_d object.\"\n    p2.append(three_d(5,6,7))                    #allocate object\nexcept MemoryError:\n    print \"Allocation error\"\n    \np1[2].show()\np2[0].show()\n\n\nfor i in xrange(2,-1,-1):\n    del p1[i]                                     #delete array\nprint \"Deleting array of thee_d objects.\"\n\ndel p2[0]                                         #delete object\nprint \"Deleting three_d object.\"",
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": "Allocating array of three_d objects.\nConstructing 0, 0, 0\nConstructing 0, 0, 0\nConstructing 0, 0, 0\nAllocating three_d object.\nConstructing 5 , 6 , 7\n0 , 0 , 0\n5 , 6 , 7\nDestructing\nDestructing\nDestructing\nDeleting array of thee_d objects.\nDestructing\nDeleting three_d object.\n"
      }
     ],
     "prompt_number": 14
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": "",
     "language": "python",
     "metadata": {},
     "outputs": []
    }
   ],
   "metadata": {}
  }
 ]
}