[python] - Error Handling

4808 단어 pythonpython

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

좋은 웹페이지 즐겨찾기