[python] - Error Handling
Error handling
A typical example is when we wish to use user input.
- We cannot guarantee that the user will input values correctly.
- If we are not careful, user input might cause an error.
To be able to do this we surround the code that is likely to raise an error in a try, except statement.
example:
def int_exception() :
"""Asks for user input and attempts to convert it into an integer.
Returns:
int: Integer value entered by user;
or -1 if they did not enter an integer.
"""
num = input("Enter a number: ")
try :
return int(num)
except Exception :
print("{0} is not a number".format(num))
return -1
*Note that how we used except Exception, this catches any error that happens.
- However, It is not always good practice to do this,especially in complex code.
Catching Different Exceptions
It is possible to specify what errors we want to catch and deal with.
example:
def get_numbers(dividend) :
"""Asks the user repeatedly for numbers and calculates 'dividend' divided by each number.
Results of division are stored in a list. The list is returned if nothing is entered.
Parameters:
dividend (int): Number to be divided by the numbers entered by user.
Return:
list<float>: List of dividend divided by each input number.
"""
results = []
while True :
num = input("Enter Number: ")
if not num :
break
try :
num = float(num)
results.append(dividend / num)
except ValueError :
print("That is not a number")
except ZeroDivisionError :
print("Can't divide by zero")
return results
Author And Source
이 문제에 관하여([python] - Error Handling), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@heesungj7/python-CSSE1001-Error-Handling저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)