6.8 Try, Except Flashcards
What does “Try, Except” statement does?
This statement controls how the program proceeds when the error occurs
What is the syntax for “Try, Except” statement?
try:
do something
except:
do something else when error occurs
Write a script using the “Try, Except” statement
try: answer = 12/0 print (answer) except: print("An error occurred")
It will print - An error occurred as you cannot divide a number by Zero
What would you do if you want to display more specific error messages to your users, depending on the error?
One can specify the error type after the except keyword
Write a script and result using the multiple levels of Except
When is ValueError raised?
When a function receives an argument that has the right type, but an inappropriate value like when asking for a number, a letter is entered.
When is ZeroDivisionError raised?
When the program tries to divide by Zero
When is IOError raised?
It is raised when an I/O operation fails for an I/O-related reason, e.g.,”file not found”.
When is importError raised?
It is raised when an import statement fails to find the module definition.
When is IndexError raised?
When a sequence(e.g. string, list, tuple) index is out of range
When is KeyError raised?
When a dictionary key isn’t found.
When is NameError raised?
When a local or global name is not found
TypeError
When an operation or function is applied to an object of inqppropriate type
What keyword is used for the pre-defined error messages?
“as”
Give an example to display the default ValueError message.
except ValueError as e:
print(e)