11 Debugging Flashcards
How can you raise your own Exception? (Not ‘except:’)
> > > raise Exception(‘Error Message’):
e.g.:
»> if input < 2:
»> raise Exception(‘Input must be greater than 2!’):
How can you display an Error message in a more user-friendly way?
You can save the Excepetion message in a variable (e.g. ‘err’) and convert it to a string
> > > except Exception as err:
print(‘Whatever Message: ‘ + str(err))
What is the Traceback, the Callstack and when do they appear?
Traceback:
Error info given when a program crashes, incl. error message, line number that caused the errror and sequence of function calls that led to it.
Call stack:
The sequence mentioned above
They are always displayed when an error is not handled, e.g. by Exceptions
What is for user errors?
What is for programmer errors?
User Errors:
- > try & except, Exception
- > You want the code to continue working
- > Designed so, that users can see them
Programmer errors:
- > Assert statements (without try & except!)
- > You want the program to crash and to find faults fast
- > You want to “fail fast” - should only occur while program is still developed (user should never see them)
- > Helps debugging
How can you raise an assert statement?
> > > assert a > b, ‘Message’
assert statement + condition (that evaluates to True or False) + ‘,’ + message
If the condition evaluates to False, the AssertionError is raised
- What is logging
- What are the benefits
- How can you use it?
- The logging function is similar to print(): It displays specified log messages
- They can be disabled all at once, have 5 different levels and give information like timestamp etc. - so you don´t risk deleting valuable code like you do, when you remove print() calls
- import logging
logging. basicConfig(level=logging.DEBUG, format=’ %(asctime)s - %(levelname)s - %(message)s’)
And then:
logging.*(‘message’) –> e.g. logging.debug(f’Start of factorial {n}’)
How many levels exist in logging and what is it useful for?
5x levels: logging.*(‘message’)
* .debug() lowest level - used for diagnose etc,
.info()
.warning()
.error()
.critical() highest level - used to indicate fatal error
Useful for:
Logging messages can be disabled:
»>logging.disable(logging.*)
Here you can define what levels should be disabled, e.g. everything up to chritical?
How can you log to a file instead of to the screen?
Add the information to the logging.basicConfig() function (see: filename=’XY.txt’):
logging.basicConfig(filename=’myProgramLog.txt’, level=logging.DEBUG, format=’
%(asctime)s - %(levelname)s - %(message)s’)