Python Exception Handling
Python Exception Handling
Exceptional Handling
• General Meaning : An exception is
something that is left out or not done on
purpose.
• https://www.programiz.com/python-program
ming/exception-handling
Prepared By: Bibek Sah
Exception
What is an Exception?
An exception in Python is an incident that happens while executing a
program that causes the regular course of the program's commands to
be disrupted.
When a Python code comes across a condition it can't handle, it
raises an exception. An object in Python that describes an error is
called an exception.
When a Python code throws an exception, it has two options: whether
handle the exception immediately or stop and quit.
In case of python, When the interpreter identifies a statement that has an error,
syntax errors occur. Consider the following scenario:
Code Output
Code Output
In Python, we catch exceptions and handle them using try and except code blocks.
The try clause contains the code that can raise an exception, while the except
clause contains the code lines that handle the exception. Let’s see an example.
# Example
# Example
Code Output
The finally keyword is available in Python, and it is always used after the try-except
block. The finally code block is always executed after the try block has terminated.
# Example