Final thoughts

It's important to reiterate that exceptions don't always have to resolve errors. Since they function like if...else blocks, they can be used in a similar manner. For example, the end-of-file exception (EOFError) can be used to identify when the last line of a file has been processed, thereby breaking out of the processing loop.

One possible use of this is to analyze strings. If a string method won't work for you, you can generally accomplish the same goal using exceptions. For example, if you want to determine if a string value is a float, you can't use the str.isdigit() method to do the job; it can only tell you if a particular string entry matches the values 0-9. If you have a floating-point number, which includes a decimal point, the isdigit() method gives you an error.

In this case, you can simply check whether the value is a float and expressly check for the error, as demonstrated here:

1 def float_check(num):
2 try:
3 float(num)
4 except ValueError:
5 print("Not a float number.")

In this example, if you check a string and it doesn't match a floating-point number, or can't be converted into a float, you receive ValueError, alerting you to the fact that the value is not a float, as shown in following screenshot:

Float check output

When using input() to receive captured information from the user, the information received is saved as a string. In this case, the input for line 11 was an imaginary number, which can't be converted to a float value and the error message was printed in line 12. But when an integer is provided in line 13, Python can convert it to a floating-point number and no error is generated.

An easier way to perform this check, without using exceptions, is shown here:

if type(num) is not float: 
    print("Not a float number.") 

In other languages, normal programming practice is to use exceptions for exceptional cases: if something goes wrong, there is a serious problem; otherwise, continue normal operations. Python programming is different, where the assumption is that valid data is present and, if not, an exception is generated and caught. In the end, the choice is up to you; use what makes the most sense and is most readable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset