Total Pageviews

2016/03/07

[Python] Exception Handling

Problem
Here is my Python program:
1
2
3
4
5
6
def checkNum(num):
  try:
    if(num>0):
        print("* number > 0 ( you input " + str(num) + " ).")
    else:
        print("* num < 0 ( you input " +  str(num) + " ).")

The parameter in checkNum method only accept number data type. If I provide String data type...
1
2
3
4
5
6
7
8
>>> import myUtil
>>> myUtil.checkNum("-20")
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    myUtil.checkNum("-20")
  File "C:\Users\albert\AppData\Local\Programs\Python\Python35-32\lib\site-packages\myUtil.py", line 2, in checkNum
    if(num>0):
TypeError: unorderable types: str() > int()

How To
We can use try...except to do exception handling in Python program, and given more friendly exception message:
1
2
3
4
5
6
7
8
def checkNum(num):
  try:
    if(num>0):
        print("* number > 0 ( you input " + str(num) + " ).")
    else:
        print("* num < 0 ( you input " +  str(num) + " ).")
  except TypeError as err:
    print('只接受數字型態(Only Accept Number Data Type)! ' + err.args[0])

Test:
1
2
3
4
>>> import myUtil
>>> myUtil.checkNum("-20")
只接受數字型態(Only Accept Number Data Type)! unorderable types: str() > int()
>>> 









No comments: