Error Handling | Python ProgrammingErrors are absolutely normal when programming. You may get hundred of errors while learning. Not only beginners like us. Even most advanced programmers get them. Now the scope of this tutorial is not teaching to code without getting errors. You can write a stable program after correcting syntax errors. But it's still possible to get a run time error while a user run it. So you have to try to avoid that kind of failures in your tools and script. Let's take an example to clear it.
This script will take two inputs and convert them to floats. After it divide first number by second number. Finally it'll print out the value. When we enter two numbers it will calculate division of those numbers. What happens if we enter an string that cannot convert to a float? So how we can escape that and write a stable script?
print('This tool will divide two numbers ') x = float(input('Enter first number : ')) y = float(input('Enter second number : ')) z = x / y print ('value of x / y is %r' %z)
Let's write above code with exceptions.
try: #hear go the normal code except: #hear we say what to do if above code is not success
Now there is another point. You know that according to math we can't device something by zero. (If y = 1/x , when limit of x goes to zero y goes to infinity, but x cannot be zero. If x is zero y then is undefined) so if user input zero as second number, our program will throw an error. Now we want to correct this one to. We can't make foolish assumptions like 'user know basic math so he 'll not enter zero as the second value'. We must escape every possible run time errors.
print('This tool will divide two numbers ') try: x = float(input('Enter first number : ')) y = float(input('Enter second number : ')) except: print ('please enter a valid value') z = x / y print ('value of x / y is %r' %z)
Now you have a good understand of error handling. Not only in mathematical operations. You want to avoid run time errors when following tasks.
print('This tool will divide two numbers ') try: x = float(input('Enter first number : ')) y = float(input('Enter second number : ')) except: print ('please enter a valid value') try: z = x / y except: print ('you can\'t device by zero') print ('value of x / y is %r' %z)
- opening a web page
- opening/writing to / reading from a file
- Going through a user supplied path
- Sending requests to a server. (You can't assume server may always up and respond your request)
This is the second tutorial of our PHP+MySQL tutorial serious.In last tutorial we saw that how we....