What is an error in a
program?
Can you name the common
types of errors you have
seen in python?
• SyntaxError
Common • TypeError
Types of • NameError
Errors in • IndexError
Python
• ValueError
• KeyError
• ZeroDivisionError
What happens when an
error occurs in a program?
Error changes the normal
flow of execution of the
program
Syntax Error is caused by the
wrong syntax in the [Link]
leads to termination of the
program. It is also known as
parsing errors.
Runtime Error occurs at
[Link] errors are
called exceptions.
What is an exception?
How is an exception invoked?
What is exception handling?
How can we handle exception in python?
An Exception is an event which occurs during
the execution of the program that interrupts
the normal flow of execution of the program.
Exceptions are invoked when the program is
syntactically correct but the code results in a
error.
Exception handling in Python is a mechanism to
handle runtime errors or exceptions, allowing
the program to gracefully handle and recover
from errors. Python provides a built-in try-
except-finally block for exception handling.
Code to
handle
the
exceptions
is
written in
the
except
block
Now let us explore
exception handling in
python
By using exception handling, we can
- Prevent program crashes
- Provide user-friendly error messages
Fill in the blanks:-
Fill in the blanks:-
Predict the output:
Output:
Fix the code to handle the errors
Use a try-except block to handle the Keyerror
and return a value 0 if the key is missing
Catching Exceptions
While executing the program, if an exception is
encountered, further execution of the code inside
the try block is stopped and the control is
transferred to the except block.
A try statement may have more than one except
statement
• IOError
• KeyboardInterrupt
• ImportError
Few • EOFError
other
• IndentationError
errors
Conclusion
• Each time an error is detected in a program, the python
interpreter raises an exception.
• Once an exception is raised ,no further statement in the
current block of code is executed.
• We can have multiple except clauses in try
• else and finally is optional clause
• finally should always be placed at the end of try clause,
after all except blocks and the else block