Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Combining try, except and finally in Python

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 397
    Comment on it

    An error that occurs during the execution of a computer program is known as exception.
    Exceptions are known to non-programmers as instances that do not conform to a general rule.
    The code, which harbours or blink the risk of an exception, is fixed in a try block

    Let's take a simple example. Lets ask the user to enter an integer number. If we use a raw_input(), the input will be a string, which we have to cast into an integer. If the input is not a valid integer then exception will generate (raise) a ValueError.

    Try and Catch: First we will use try if there is any error in a python program and after then we will use catch and at last we will use exception.
    Finally: Finally is used every time before leaving the try statement even if exception occurs or not. The error will be re-raised when final clause is executed only if the exception occured in try which is not handled by except clause.
    Example:

    inputVal = int(raw_input("Please enter a number: "))
    Please enter a number: 34.5
    ValueError: invalid literal for int() with base 10: '34.5'
    File "C:\Personal\PythonScript\python-ppt\TechTra\setExample.py", line 39, in 
    inputVal = int(raw_input("Please enter a number: "))
    With the aid of exception handling, we can write robust code for reading an integer from input:
    while True: 
    try: inputVal = raw_input("Please enter an integer: ") 
    inputVal = int(inputVal ) 
    break 
    except ValueError: 
    print("No valid integer! Please try again ...") 
    print "Great, you successfully entered an integer!" 

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: