Exception Handling
Exception Handling
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.
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.
User-Defined Exceptions.
Raising Exceptions
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
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")
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
File c:\users\pc\desktop\untitled43.py:6
raise KeyError("Keys not present in dictionary")
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)
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
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
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
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