0% found this document useful (0 votes)
13 views6 pages

Python Try Exception

The document provides an overview of exceptions in Python, detailing types of errors such as syntax errors, run-time errors, logical errors, and common examples like ZeroDivisionError and ValueError. It explains how to handle exceptions using try-except blocks, including the use of else and finally clauses for better error management. Additionally, it illustrates how to handle specific exceptions separately for more precise error handling.

Uploaded by

angelasunil2008
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views6 pages

Python Try Exception

The document provides an overview of exceptions in Python, detailing types of errors such as syntax errors, run-time errors, logical errors, and common examples like ZeroDivisionError and ValueError. It explains how to handle exceptions using try-except blocks, including the use of else and finally clauses for better error management. Additionally, it illustrates how to handle specific exceptions separately for more precise error handling.

Uploaded by

angelasunil2008
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Notes Class XII Exception

When ever one writes a program, there are possibilities of error – it will extremely difficult to write an
error free code. A Python program (script) may have:
• Syntax error – when the rule of the programing language is violated. Before the execution of program,
Python checks for syntax error.
• Run-time error – error triggered during the execution of program causing the program to halt abruptly.
Run-time error is triggered because the program encounters unexpected data during the run-time. An
error message is displayed by Python after a run-time error. Every run-time error has a name.
• Logical error – most difficult error to detect. Gives unexpected output / result during the run-time
because of flaw in the design or flaw in the logic. Logical error may trigger run-time error.

Some common runtime errors are discussed below:


• Syntax Error, Name Error and Type Error
x=100
y=input('Value / Expression / Variable Name? ')
s=x+eval(y)
print(s)

Running of the script


Value / Expression / Variable Name? 200
300
Variable x is 100 and eval(y) is 200 and hence s is 300.

Running of the script


Value / Expression / Variable Name? 10+20+30
160
Variable x is 100 and eval(y) is 30(10+20+30) and hence s is 160.

Running of the script


Value / Expression / Variable Name? x
200
Variable x is 100 and eval(y) is x (x is a valid variable name and x is defined) and hence s is
200 (x+x is 200).

Running of the script


Value / Expression / Variable Name? 3z
Traceback (most recent call last):
File "D:\Python\[Link]", line 3, in <module>
s=x+eval(y)
File "<string>", line 1
3z
^
SyntaxError: unexpected EOF while parsing
Variable x is 100 but eval(y) is 3z. According to Python 3z is not a correct variable name. Hence
a runtime error.

Running of the script


Value / Expression / Variable Name? z3
Traceback (most recent call last):
File "D:\Python\[Link]", line 3, in <module>
s=x+eval(y)
File "<string>", line 1, in <module>
NameError: name 'z3' is not defined
FAIPS, DPS Kuwait Page 1 / 6
Python Notes Class XII Exception
Variable x is 100 but eval(y) is z3. z3 is a valid variable name but Python is unable to identify
z3 because z3 is not defined. Hence the runtime error.

Running of the script


Value / Expression / Variable Name? y
Traceback (most recent call last):
File "D:\Python\[Link]", line 3, in <module>
s=x+eval(y)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Variable x is 100 but eval(y) is y. y is a valid variable name and defined but x and y cannot be
added because x is int and y is str. Hence the run-time error.

• Zero Division Error


x=100
y=input('Value / Expression / Variable Name? ')
z=x/eval(y)
print(z)

Running of the script


Value / Expression / Variable Name? 25
4.0
Variable x is 100 and eval(y) is 25 and hence z is 4.0. So long the inputted value/expression is
non-zero, expression x/eval(y) will give correct result.

Running of the script


Value / Expression / Variable Name? 12+8
5.0
Variable x is 100 and eval(y) is 20 (12+8) and hence z is 5.0.

Running of the script


Value / Expression / Variable Name? 0
Traceback (most recent call last):
File "D:\Python\[Link]", line 3, in <module>
z=x/eval(y)
ZeroDivisionError: division by zero
Variable x is 100 and eval(y) is 0. When using operators /, // and %, if the second operand is
zero, it will trigger a runtime error.

• Value Error
import math
x=eval(input('Value / Expression / Variable Name? '))
y=[Link](x)
print(y)

Running of the script


Value / Expression / Variable Name? 25
5.0
eval(x) is 25, square root of 25 is 5.0 and hence y is 5.0. So long the inputted value/expression
is non-negative, [Link](x) will give correct result.

Running of the script


Value / Expression / Variable Name? -25
FAIPS, DPS Kuwait Page 2 / 6
Python Notes Class XII Exception
Traceback (most recent call last):
File "D:\Python\[Link]", line 3, in <module>
y=[Link](x)
ValueError: math domain error
eval(x) is -25, [Link]() cannot calculate square root of -25 and hence run-time error.

• Index Error
alist=[23,67,45,74]
print(alist[5])

Running of the script


Traceback (most recent call last):
File "D:\Python\[Link]", line 2, in <module>
print(alist[5])
IndexError: list index out of range
When accessing an element of a list (tuple), correct index of an element in a list (tuple) is 0 to length
of (lust/tuple) – 1. List alist has 4 elements, index varies from 0 to 3. Hence index 5 is out of range.

• File Not Found Error


df=open('[Link]')
data=[Link]()
[Link]()
print([Link]())

Running of the script


Traceback (most recent call last):
File "D:\Code\Python\[Link]", line 1, in <module>
tf=open('[Link]')
FileNotFoundError: [Errno 2] No such file or directory: '[Link]'
Opening a file '[Link]' in read mode when the file does not exist, will trigger a run-time error.

In Python all the run-time errors are called exception. Very few exceptions can be eliminated by using an
if-else statement. So, Python provides an alternative way to handle an exception. Using try statement with
except clause one can handle any exception. try-except can be used in the following way:
• Syntax #1
try:
Action1
except:
Action2
[else: Action3]
[finally: Action4]

try, except, else and finally are all keywords. A try statement must have at least one except clause.
else clause and finally clauses are optional.

Action after try may trigger an exception. If Action1 after try triggers an exception, then control
jumps to except clause and Action2 is executed. If Action1 after try does not trigger any exception,
then control jumps to else clause and Action3 is executed. finally clause is always executed, whether
Action1 triggers an exception or not.

x=input('Number? ')
try:
FAIPS, DPS Kuwait Page 3 / 6
Python Notes Class XII Exception
y=100/eval(x)
except:
print('Error')

Running of the script


Number? 0
Error
Inputted value of x is '0' and eval(x) is 0. Statement after the try triggers
ZeroDivisionError exception and control jumps to except clause and the statement after except
clause is executed.

Running of the script


Number? 25
When statement after the try does not trigger any exception and script does not do anything. Modified
Python script is given below with else clause.
x=input('Number? ')
try:
y=100/eval(x)
except:
print('Error')
else:
print('Quotient=',y)

Running of the script


Number? 25
Quotient= 4.0
Statement after the try does not trigger any exception. Control jumps to the else clause and statement
after the else clause is executed. except clause will handle all exceptions triggered by the statement
after try.

Running of the script


Number? z
Error
Inputted value of x in 'z' and eval(x) is z. Variable z is not defined. Statement after the try
triggers NameError exception and control jumps to the except clause.

Running of the script


Number? 10z
Error
Inputted value of x in '10z' and eval(x) is 10z. 10z is neither an expression nor a variable not
defined. Statement after the try triggers SyntaxError exception and control jumps to the except
clause.

Running of the script


Number? x
Error
Inputted value of x in 'x' and eval(x) is x. x is a string variable (str type). Statement after the try
triggers TypeError exception and control jumps to the except clause.

As discussed earlier, finally clause always get executed, whether exception is triggered or not. Edited
Python script with finally clause is given in the next page.

FAIPS, DPS Kuwait Page 4 / 6


Python Notes Class XII Exception
x=input('Number? ')
try:
y=100/eval(x)
except:
print('Error')
else:
print('Quotient=',y)
finally:
print('End of script')

Running of the script


Number? 20
Quotient= 5.0
End of script
The statement after the try does not trigger any exception. Control jumps to the else clause and the
statement after the else clause is executed. finally clause always gets executed.

Running of the script


Number? 0
Error
End of script
Inputted value of x in '0' and eval(x) is 0. Statement after the try triggers
ZeroDivisionError exception and control jumps to the except clause and the statement after the
except clause is executed. finally clause always gets executed. If the predefined Python exceptions
are to handled separately, then we have to use second syntax of try-exception.

• Syntax #2
try:
Action1
except exception1:
Action2
except exception2:
Action3
:
[else: Action4]
[finally: Action5]

Only difference in the second syntax, after the except clause, predefined Python exception are handled
separately. Modified Python script is given below:

x=input('1st Number? ')


y=input('2nd Number? ')
z='ZERO'
try:
q=eval(x)/eval(y)
except SyntaxError:
print('Incorrect variable name')
except NameError:
print('Variable not defined')
except TypeError:
print("Cannot divide 'int' and 'str'")
except ZeroDivisionError:
print('Division by zero')
FAIPS, DPS Kuwait Page 5 / 6
Python Notes Class XII Exception
else:
print('Quotient=',q)
finally:
print('End of script')

Running of the script


1st Number? 100
2nd Number? 25
Quotient= 4.0
End of script

Running of the script


1st Number? 100
2nd Number? 30a
Incorrect variable name
End of script

Running of the script


1st Number? 100
2nd Number? deno
Variable not defined
End of script

Running of the script


1st Number? 100
2nd Number? z
Cannot divide 'int' and 'str'
End of script

Running of the script


1st Number? 100
2nd Number? 0
Division by zero
End of script

FAIPS, DPS Kuwait Page 6 / 6

You might also like