Raising and Handling Exceptions Flashcards
Exception
An event or error that may cause your program to stop if not properly handled.
“The user provided the wrong data type causing the Traceback to throw a TypeError exception.”
Exception Name: NameError
A local or global name is not found.
Exception Name: ZeroDivisionError
The second argument of a division or modulo operation is zero.
Exception Name: OverflowError
The result of an arithmetic operation is too large to be represented.
Exception Name: SyntaxError
The parser encounters a syntax error.
Exception Name: TypeError
An operation or function is applied to an object of inappropriate type.
Exception Name: KeyboardInterrupt
The user hits the interrupt key (normally Control-C or Delete).
TRY and EXPECT
we can handle exceptions using the try and except syntax. try: if x < 0: raise ValueError(f"x is too small") ^raise generates the exception except ValueError as problem: then do something to handle the exception like print(:we had an exception"
try:
and
Body of the try-clause
This begins a try-clause. If any exception is raised by any code executed inside the try-clause, the rest of the try-clause is skipped, and code execution moves to the except clause.
The try-clause should include all code that has the possibility of raising an exception that we want to handle. The try-clause is indented once from try:
except
A keyword that begins an except-clause. The except-clause will run if a matching exception is raised from the try-clause.
ExampleError
Replace this with the type of exception that we are handling, such as NameError or ZeroDivisionError.
as
A keyword that designates the caught exception (that matches the type of ExampleError) can be accessed as the local variable to the right.
error_as_a_variable:
Replace this with any valid variable name. This variable’s value will be the exception data, and can be accessed inside of the except-clause. err is a common variable name. Don’t forget the :!
Body of the except clause
The error clause should include code that needs to execute if an exception is raised. This code can be used for printing or logging details about err. More powerfully, this is where we can try handling the situation and helping the program move on.
Handling Multiple Types of Exceptions
If we need to handle more than one kind of exception, we can add an infinite number of except clauses. Much like the if..elif statements, the raised exception will check if it matches one-at-a-time, starting from the top.