An exception is an error that happens during the execution of a program. Exceptions are known to non-programmers as instances that do not conform to a general rule.
The code, which harbours the risk of an exception, is embedded in a try block
Let's look at 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.
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:
0 Comment(s)