Topic : Exceptional 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.
Prepared By: Bibek Sah
Exception Vs Syntax Error
Prepared By: Bibek Sah
Exception Vs Syntax Error
In case of python, When the interpreter identifies a statement that has an error,
syntax errors occur. Consider the following scenario:
Code Output
Prepared By: Bibek Sah
Exception
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. In general, when a Python
script encounters a situation that it cannot cope with, it raises an exception. An
exception is a Python object that represents an error.
Code Output
Prepared By: Bibek Sah
Exception (Different Types)
Python Logical Errors (Exceptions)
Errors that occur at runtime (after passing the syntax test) are called exceptions or
logical errors.
For instance, they occur when we
try to open a file(for reading) that does not exist (FileNotFoundError)
try to divide a number by zero (ZeroDivisionError)
try to divide a number by zero (ZeroDivisionError)
set of code inside the IndexError exception is executed
try to import a module that does not exist (ImportError) and so on.
Whenever these types of runtime errors occur, Python creates an exception object.
If not handled properly, it prints a traceback to that error along with some details
about why that error occurred.
Prepared By: Bibek Sah
Exceptional Handling
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
Prepared By: Bibek Sah
Exceptional Handling
# Example
Code Output
Prepared By: Bibek Sah
Finally Keyword in Python
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.
Here is an example of finally keyword with try-except clauses:
Prepared By: Bibek Sah
Finally Keyword in Python
# Example
Prepared By: Bibek Sah