-
Notifications
You must be signed in to change notification settings - Fork 0
/
exceptions_and_exception.py
69 lines (49 loc) · 1.55 KB
/
exceptions_and_exception.py
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
#!python/usr/bin
"""Exceptions and Exception:
Identifying exceptions (errors)
Trapping exceptions with try/except
Raising exceptions with raise
Defining custom exception classes"""
"""lesson 1: Trapping and raising exceptions"""
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# key = raw_input('please input a key: ')
try:
print('testing for error')
print("the value for {0} is {1}".format(key, my_dict[key]))
print('everything is ok')
except KeyError:
print('trapped error')
print("the key " + key + " does not exist")
print('program continues ...')
another way
import sys
try:
arg = sys.argv[1]
num = int(arg)
except(IndexError, ValueError):
exit('please enter an integer on the command line')
print "thanks for the int"
"""lesson 2: custom exceptions"""
import re
def process_date(this_date):
# this regex makes sure that this_date is YYYY-MM-DD
if not re.search(r'^\d\d\d\d\-\d\d\-\d\d$', this_date):
raise ValueError('please submit date in YYYY-MM-DD format')
print "the submitted dates is {0}".format(this_date)
process_date('1980-01-03')
print
class MyError(Exception):
def __init__(self, *args):
print 'calling init'
if args:
self.message = args[0]
else:
self.message = None
def __str__(self):
print "calling str"
if self.message:
return "here's a MyError exception with a message: {0}".format(self.message)
else:
return "here's a MyError exception!"
#raise MyError
raise MyError('Houston, we have a problem')