0% found this document useful (0 votes)
18 views

Exception Handling

Uploaded by

Nirmal Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Exception Handling

Uploaded by

Nirmal Pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Exception Handling

While executing a Python program, it may happen that the program


does not execute at all or it can generate unexpected output. This
happens when there are syntax errors, run time errors, logical errors or
any semantic errors in the code.

1. Syntax error
It occurs when we put some incorrect punctuation, incorrect word
sequence or there are some undefined terms or missing parenthesis.
Syntax errors are also called as Parsing errors.
For example:
>>> p=2(num1+num2)
This statement is mathematically correct but python interpreter will
raise SYNTAX error as there is no sign present between 2 and
parenthesis. The correct statement will be:
>>> p=2*(num1+num2)

2. Semantic error
It occurs when the code is correct according to syntax but it is not
meaningful. The code will not behave as expected.
For example:
A = 10
B = “hello”
Result = A + B
Here, the code will execute as it has correct syntax but will not generate
expected output.
3. Logical error
It may occur when there may be some improper sequence of statements
or incorrect use of operator. It will not stop a program from executing
but will produce incorrect output. It will generate incorrect output for
every value of input.
For example:
If we want to find sum of two numbers and write the following code:
A, B = 10, 15
C=A*B
print (“Sum is:” , C)
Here, the code will generate A * B but we wanted to find Sum. Hence it
is a logical error.

4. Run time error


It occurs at the time of program execution. Such errors produce incorrect
output for specific values of input. These errors are also called Exceptions,
which occur when something unexpected happens leading to stop the
program execution.
For example:
 Division by zero
 Finding square root of negative number.
 Insufficient memory available on computer.
 Trying to open a file that does not exist.

Exceptions:
Run time errors are known as Exceptions.
When an Exception is generated, the program execution is stopped.
Removing errors from a code is referred to as Exception Handling.

Commonly occurring exceptions are usually defined in the Interpreter.


These are known as Built-in Exceptions.

Some Built-in Exceptions are listed as below:


Exception Description
ZeroDivisionError It is raised when an expression or a value is
getting divided by zero (0). For example: If c =
0, then p = b/c will result in
‘ZeroDivisionError’.
NameError It is raised when a local or global variable
name is not defined.
It is raised when an identifier is not assigned
any value earlier and is being used in some
expression. For example: p = a*b/c then it will
result in ‘NameError’ when one or more
variables are not assigned values.
TypeError It is raised when an operator is supplied with a
value of incorrect data type.
It is raised when variables used in any
expression have values of different data types.
For example: p=(a+b)/c then it will result in
‘TypeError’ when the variables a, b and c are
of different data types.
Value Error It is raised when given value of a variable is of
right data type but not appropriate according
to the expression.
IOError It is raised when the file specified in a program
statement cannot be opened.
IndexError It is raised when index of a sequence is out of
the range.

KeyError It is raised when a key doesn’t exist or not


found in a dictionary.
SyntaxError It is raised when there is an error in the
syntax of the Python code
KeyboardInterrupt It is raised when the user accidentally hits the
Delete or Esc key while executing a program
due to which the normal flow of the program is
interrupted
ImportError It is raised when the requested module
definition is not found.
EOFError It is raised when the end of file condition is
reached without reading any data by input().
IndentationError It is raised due to incorrect indentation in the
program code.
OverFlowError It is raised when the result of a calculation
exceeds the maximum limit for numeric data
type.

User-Defined Exceptions.

A programmer can also create custom exceptions to suit one’s


requirements. These are called user-defined exceptions.

Raising Exceptions

Each time an error is detected in a program, the Python interpreter


raises (throws) an exception.

User-defined exceptions can be created using two methods

1. raise statement
2. assert statement

In other words we can say that the Programmers can also forcefully
raise exceptions in a program using the raise and assert statements.
raise Statement

The raise statement can be used to throw an exception. The syntax of


raise statement is:

raise exception-name[(optional argument)]


The optional argument is generally a string that is displayed as message
when the exception is raised.

Ex:1
age=int(input("Enter your age"))
if age<0:
raise Exception("Age cannot be negative")
elif age>=18:
print("You are eligible for voting")
else:
print("You are not eligible for voting")
Output:
Enter your age-9
Traceback (most recent call last):

File C:\Program
Files\Spyder\pkgs\spyder_kernels\py3compat.py:356 in compat_exec
exec(code, globals, locals)

File c:\users\pc\desktop\untitled42.py:3
raise Exception("Age cannot be negative")

Exception: Age cannot be negative

Ex:2
d={'A':4,'B':10}
k=input("Enter key to search:")
if k in d.keys():
print("Keys found in dictionary")
else:
raise KeyError("Keys not present in dictionary")
Output:
Enter key to search:A
Keys found in dictionary

Enter key to search:G


Traceback (most recent call last):
File C:\Program
Files\Spyder\pkgs\spyder_kernels\py3compat.py:356 in compat_exec
exec(code, globals, locals)

File c:\users\pc\desktop\untitled43.py:6
raise KeyError("Keys not present in dictionary")

KeyError: 'Keys not present in dictionary'

The assert Statement

An assert statement in Python is used to test an expression in the


program code. If the result after testing comes false, then the exception
is raised.

assert Expression[,arguments]
On encountering an assert statement, Python evaluates the expression
given immediately after the assert keyword. If this expression is false,
an AssertionError exception is raised which can be handled like any
other exception.

def odd_even(n):
assert (n%2==0),"Pass Even Numbers"
print("Even Number")
odd_even(6)
odd_even(5)
Output:
Even Number
Traceback (most recent call last):

File C:\Program
Files\Spyder\pkgs\spyder_kernels\py3compat.py:356 in compat_exec
exec(code, globals, locals)

File c:\users\pc\desktop\untitled45.py:5
odd_even(5)

File c:\users\pc\desktop\untitled45.py:2 in odd_even


assert (n%2==0),"Pass Even Numbers"

AssertionError: Pass Even Numbers

Every exception has to be handled by the programmer for successful


execution of the program. To ensure this we write some additional code
to give some proper message to the user if such a condition occurs. This
process is known as Exception Handling.

In Python, exceptions are handled by using try-except-finally block.


While writing a code, programmer might doubt a particular part of code
to raise an exception. Such suspicious lines of code are considered inside
a try block which will always be followed by an except block.
The code to handle every possible exception, that may raise in try block,
will be written inside the except block.
If no exception occurred during execution of program, the program
produces desired output successfully.

But if an exception is encountered, further execution of the code inside


the try block will be stopped and the control flow will be transferred to
the except block.

Ex:
a=int(input('Enter first no:'))
b=int(input('Enter second no:'))
try:
result=a/b
print("Division result is:", result)
except ZeroDivisionError:
print("Denominator is zero !! Division not possible.")

Output:
Enter first no:25
Enter second no:6
Division result is: 4.166666666666667

Enter first no:25


Enter second no: 0
Denominator is zero!! Division not possible.

Ex:
a=int(input("Enter a value: ")) Enter a value: ram
ValueError: invalid literal for int()
with base 10: 'ram'
In above example, the user entered a wrong value that raised
ValueError. We can handle this exception by using ValueError
exception.

try:
a=int(input("enter a value: "))
print(a)
except ValueError:
print('Wrong input! Enter only integers')
Output:
enter a value: dfg
Wrong input! Enter only integers

Use of multiple “except” block:


Sometimes, it may happen that a single piece of code in a program might
have more than one type of error. If such an event happens, we can use
multiple except blocks for a single try block.

try:
a=int(input('Enter first no:'))
b=int(input('Enter second no:'))
result=a/b
print("Division result is:", result)
except ZeroDivisionError:
print("Denominator is zero !! Division not possible.")
except ValueError:
print('Please enter only integer value')
Output:
Enter first no:24
Enter second no:5
Division result is: 4.8

Enter first no:24


Enter second no: 0
Denominator is zero!! Division not possible.

Enter first no:24


Enter second no:h
Please enter only interger value

Enter first no:rt


Please enter only interger value

try…except…else Clause:
Just like Conditional and Iterative statements we can use an optional
else clause along with the try…except clause. An except block will be
executed only when some exceptions will be raised in the try block. But
if there is no error then except blocks will not be executed. In this case,
else clause will be executed.

try:
a=int(input('Enter first no:'))
b=int(input('Enter second no:'))
result=a/b
print('Division operation performed')
except ZeroDivisionError:
print("Denominator is zero !! Division not possible.")
except ValueError:
print('Please enter only interger value')
else:
print("Division result is:", result)

Output:
Enter first no:24
Enter second no:4
Division operation performed
Division result is: 6.0

finally CLAUSE:
The try…except…else block in python has an optional finally clause. The
statements inside the finally block are always executed whether an
exception has occurred in the try block or not. If we want to use finally
block, it should always be placed at the end of the clause i.e. after all
except blocks and the else block.

try:
a=int(input('Enter first no:'))
b=int(input('Enter second no:'))
result=a/b
print('Division operation performed')
except ZeroDivisionError:
print("Denominator is zero !! Division not possible.")
except ValueError:
print('Please enter only interger value')
else:
print("Division result is:", result)
finally:
print('Have a good day')
Output:
Enter first no:24
Enter second no:5
Division operation performed
Division result is: 4.8
Have a good day

You might also like