Exception Handling in Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Exception Handling in

Python
BY: Preeti Dalal,
Lecturer Computer Science
What is Debugging? What are the various types of
errors in Python?
The process of finding errors in a program is termed as Debugging. For successful
execution of a program it is necessary to find and remove errors. In Python, errors
are classified as:

1. Syntax error
2. Logical error
3. Run-Time error
Syntax Error:
Syntax errors are errors that occur due to incorrect format of a Python statement.
They occur while the statement is being translated to machine language and
before being executed. Syntax errors are also known as PARSING errors.Some
examples of syntax errors are:

1. Incorrect indentation
2. Misspelling indentation
3. Leaving out a symbol such as colon(:), comma(;) or parentheses(())
Logical Error:
Logical error occurs in Python when the code runs without any syntax or runtime
errors but always produces incorrect output due to incorrect logic used in
program. These types of errors are often caused by incorrect assumptions, an
incomplete understanding of the problem, or the incorrect use of algorithms or
formulas.
LOGICAL ERROR
Run-Time Error:
Errors that occur during program execution are known as run-time errors. These
are also known as EXCEPTIONS. These errors can occur for various reasons, such
as dividing by zero, trying to access an element in a list that doesn't exist, or
attempting to open a file that doesn't exist.
Exception Handling in Python:
An exception is an error that happens during the execution of a program. If an

exception is not caught, the program is terminated. As it interrupts the normal flow

of the program, so it needs to be handled carefully.

When an exception is raised on account of some error, the program must contain

code to catch the exception and handle it properly. In Python, we have try, except

and finally clause.


try-except-else-finally
1. The try block contain the code which may produce an error at the time of
execution. If there is no exception, full try block will be executed and except
block will not be executed. But if there is an exception, execution of try block
will be stopped immediately and except block will get executed.
2. The except block will be executed only if there is an exception as it contains the
code to handle the exception occurred in try block.
3. The else block will get executed if there is no exception.
4. The finally block comes after all try and except blocks. The statements in finally
block will get executed irrespective of whether an exception occurs or not.
Examples:

You might also like