In lesson 4, or chapter 3 you have seen the most common use of the try except (without the finally).
You can see here that the program will run the code in the try, and check if an error occurs. If an error happens with the code in the try, then none of the code in that block is used- avoiding a crash- and the code in the except block is executed.
The finally block gets executed regardless of which - the try or the except - gets executed. This is not a common use-case, but it can be useful when the need arises.
A detailed explanation may be found here.
try:
statement_one # 1
statement_causing_exception # 2
statement_not_evaluated # 3
except Exception as error:
print(f"Failed- {error} was raised")
In the example shown as a typical application, the try block executes the first statement successfully, and then encounters an error with the second.
While we could have just used except: this is considered poor practise, so what we are doing is assigning an alias to whatever Exception is raised, and in the following print function, letting the user know what that error was- in preference to silently handling it in this case.
rate = input("Enter the rate per hour: )
try:
rate = float(rate)
if rate < 0:
raise ValueError("Value cannot be negative")
except Exception as error:
print(f"Failed- {error}")
Here in a concrete example from a function asking the user to enter a rate for a wages program. Now, if the user enters '12' or any valid positive number, inside the try block:
rate gets converted to a float- 12.0
the rate passes the checkpoint looking for a negative value
Program flow continues on in the main program.
If the user enters 'cat', inside the try block:
the attempt to convert to a float fails
the except block is executed, and the following message is output:
Failed- could not convert string to float: 'cat'
If the user enters a value which will result in a negative float, such as '-8', then inside the try block:
the rate successfully gets converted to -8.0
the check for a negative value is found to be True, triggering the raising of a ValueError.
The ValueError message is passed to the except block and the following message is output:
Failed- Invalid value- cannot be negative
Python can chain many except clauses after a single try, handling differently any or many different types of exceptions in different ways. While one can raise errors and halt program execution, we can also quietly handle errors with our code.