Module 11 - Exceptions Flashcards
What is an exception?
Error that occurs while a program is running
Usually causes program to abruptly halt
What is a traceback?
Error message that gives information regarding line numbers that caused the exception
Tells you type of exception and brief description of the error
What are some examples of exceptions that cannot be avoided by careful coding?
Trying to convert non-numeric string to an integer
Trying to open for reading a file that doesn’t exist
What is an exception handler?
Code that responds when exceptions are raised and prevents program from crashing
What is the exception handler statement in Python?
try/except statement
try:
___statements
except exceptionName:
___statements
How does the try/except statement work?
You can enter whatever code you want in the 'try' suite The handler (i.e., the except block) will execute if the 'try' suite has an exception If no exception is raised, handler is skipped
Which three steps are KEY in writing professional grade exception handling code?
- Account for unavoidable exceptions (adding the except statement)
- Inform the end user that an error has occurred by displaying a USER FRIENDLY message
- Take further action by retrying or saving existing work when possible and if applicable
Often code in try suite can throw more than one type of exception. How do you handle this?
Need to write except clause for each type of exception that needs to be handled
What happens when an except clause does not list a specific exception?
It will handle ANY exception raised in the ‘try suite’
Should always be last in the series of except clauses!
What is an exception object?
Object created in memory when an exception is thrown
It contains a default error message pertaining to the exception
What can you do with an exception object?
Can assign the exception object to a variable in an except clause
Example: except ValueError as err:
Can pass exception object variable to print function to display the default error message
What is the ‘else’ clause?
Optional block of code AFTER the try and except blocks that runs IF there are no exceptions
(if exceptions, else suite is skipped)
What is the ‘finally’ clause?
Optional block of code AFTER the try and except blocks - execute whether an exception occurs or not.
Purpose is to perform cleanup before exiting.
finally:
___statements
What are the two ways for an exception to go unhandled?
- No except clause specifying exception of the right type
2. Exception raised outside a try suite
What happens when an exception goes unhandled?
Exception will cause the program to halt