Exceptions in Python
#Syntax error or
compilation time error
#Example 1: even or odd number
a=int(input("enter any
number"))
if a%2==0 #syntax error due to
colon is missing
print(a," is even number")
"""output:
If a%2
Syntax error, but rectified
enter any number4
4 is even number
"""
Example 2: Logical
error
#Example2:To increment the
salary of 20%
def promo(sal):
#sal=sal*20/100 #Logical error
sal=sal+sal*20/100
return sal
sal=promo(5000.00)
print('incremented salary=%.2f' %sal)
"""output:
#incremented salary=1000.00
incremented salary=6000.00
"""
Runtime Error
#Example 3:add two strings
def concat(a,b):
print(a+b)
#call the concat() function
concat("hyder","abad")
concat("pawan","kalyan")
concat("hyder",25)
"""output:
hyderabad
pawankalyan
Runtime error
"""
Errors in Python:
Error is an action which is
incorrect/mistake or inaccurate is called error.
3 types of errors:
1.
Compile time
error(Syntax error)
2. Logical Error
3.
Runtime error
(Exception)
Compile time
error(Syntax error)
The error which occurs because
of invalid syntax is called compile time error. We can correct the syntax
error.
Ex: 10=a
Forgetting the colon in the
statement like ‘if,while,for, in the function. Such kinds of errors are
detected by python compiler.
#Example 1: even or odd number
a=int(input("enter any
number"))
if a%2==0 #syntax error due to
colon is missing
print(a," is even number")
"""output:
If a%2
Syntax error, but rectified
enter any number4
4 is even number
"""
2. Logical error:
These errors occurs in the
logic of the program. Example developer may write the wrong formula or the
program design is wrong.
We can correct the logical
error.
Example: After incrementing
the 20% of the salary
Sal=sal*20/100
Actual
formula is sal=sal+sal*20/100
#Example2:To increment the
salary of 20%
def promo(sal):
#sal=sal*20/100 #Logical error
sal=sal+sal*20/100
return sal
sal=promo(5000.00)
print('incremented salary=%.2f' %sal)
4. Runtime error (Exceptions)
It is also known as
Exceptions. While executing the program if something goes wrong because of
client input or memory problem then we will get run time errors
We can not correct the
program.
#Example 3:add two strings
def concat(a,b):
print(a+b)
#call the concat() function
concat("hyder","abad")
concat("pawan","kalyan")
concat("hyder",25)
"""output:
hyderabad
pawankalyan
Runtime error
Related Video: https://youtu.be/TeVaBIo-WQo
Next: Exception Handling part1
Prev:Packages
https://youtu.be/dNhqP7PHcws
No comments:
Post a Comment