Lecture 7 Flashcards
exception handling, pdb
raise keyword
syntax
raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program
raise ExceptionType(“user text”)
how do you raise an exception?
raise keyword
how does try() work? (5)
1 First, the try clause is executed i.e. the code between try.
2 If there is no exception, then only the try clause will run, except clause is finished.
3 If any exception occurs, the try clause will be skipped and except clause will run.
4 If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.
5 A try statement can have more than one except clause
how do you pass a handful of exceptions?
by passing a TUPLE of errors into the except block
ex
try:
as;kdjf
except (TypeError, AttributeError)
else clause/keyword (2)
1 must be present after all the except clauses in the code
2 The code enters the else block ONLY if the try clause does not raise an exception
finally clause/keyword (2)
1 always executed AFTER the try and except blocks.
2 finally block always executes AFTER the normal termination of the try block OR after the try block terminates due to some exceptions.
what is pdb?
1 module that comes built-in to the Python standard library
2 actually defined as the class Pdb, which internally makes use of bdb basic debugger functions and cmd (support for line-oriented command interpreters) modules
3 stands for python debugger
what are the common pdb commands? (4)
l (list) > displays where the last thing that was running.
We can type in the names of the variables to check what they actually contain.
n (next line)
p (print)
c (continue - finishes debugging)
what is the major advantage of pdb?
it runs purely in the command line, thereby making it great for debugging code on remote servers when we don’t have the privilege of a GUI-based debugger.
what is one potential issue of pdb and how do you solve it?
Sometimes the variable names might conflict with the pdb commands
For example, in the example below, c is the name of a variable and also a pdb command so it quits instead of displaying the value of the variable
This problem can be solved by adding ‘p’ before the name of the variable, here p stands for print
types of errors in python (10)
1 Syntax
2 TypeError
3 NameError
4 IndexError
5 KeyError
6 ValueError
7 AttributeError
8 IOError
9 ZeroDivisionError
10 ImportError
SyntaxError
raised from program syntax issue such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
TypeError
raised when an operation or function is applied to an object of the wrong type, such as adding a string to an integer.
NameError
raised when a variable or function name is not found in the current scope.
IndexError
raised when an index is out of range for a list, tuple, or other sequence types.