DEBUGGING/ERROR HANDLING
• The try blocks lets you test a block of code for errors.
• The except block lets you handle the error.
• The else block lets you execute code when there is no error.
• The finally block lets you execute code, regardless of the result of the try-and except
blocks.
EXCEPTION HANDLING
• When an error occurs, or exception as we call it, Python will normally stop and generate
an error message.
• These exception can be handled using the try statement:
Example: Output:
The try block will result an error because
the value of x is not defined
MANY EXCEPTIONS
• You can define as many exception blocks as you want, e.g. if you want to execute a special
block of code for a special kind of error:
Example: Output:
The try block will generate a
NameError, because x is not defined:
ELSE
• You can use the else keyword to define a block of code to be executed if no errors
were raised.
Example: Output:
The try block does not raise any errors, so the
else block is executed:
FINALLY
• The finally block, if specified, will be executed regardless if the try block raises an error
or not.
Example: Output:
The finally block gets executed no
matter if the try block raises any errors
or not:
PYTHON BUILT-IN EXCEPTIONS
COMMON PYTHON ERRORS
• SyntaxError
• A SyntaxError occurs when the Python interpreter finds code that doesn't conform to the
language's grammar rules. This often happens due to typos or incorrect punctuation.
Example: Fix:
Missing value of x and a colon at the end of the “if statement”.
INDENTATIONERROR
• is a type of SyntaxError specific to Python's reliance on whitespace for defining code
blocks. It means there's an issue with the indentation, such as an incorrect number of
spaces.
Example: Fix:
TYPEERROR
• A TypeError arises when an operation is performed on an object of an inappropriate
type. This often happens when you try to combine different data types in a way that isn't
supported.
Example: Fix:
NAMEERROR
• A NameError occurs when a variable, function, or module is not found in the current
scope. This typically means the name was misspelled or wasn't defined before being used.
Example: Fix:
Correct the spelling of the variable to match its definition.
INDEXERROR
• An IndexError happens when you try to access an index of a sequence (like a list or
string) that is out of range. Remember that indexing starts at 0 in Python.
Example: Fix:
Use a valid index within the range 0 to 2.
KEYERROR
• A KeyError is specific to dictionaries and occurs when you try to access a key that does
not exist in the dictionary.
Example: Fix:
Access a key that is present in the dictionary.
VALUE ERROR
• A ValueError is raised when a function receives an argument of the correct type but an
inappropriate value. For example, trying to convert a string to a number when the string
doesn't contain a valid number.
Example: Fix:
Ensure the string contains a valid number.