Exception Handling in Python✌
Exceptions ---> in Python
Normally error is an event that occurs when our code fails to follow the rules of a certain coding language, there are two kinds of error in python. They are,
- Syntax error
- Runtime error
Base Exception is the root of python Exception handler.
1. Normal Execution of Try-Except block
Example:
print('the try except concept')
try:
print(1/0)
except ZeroDivisionError:
print('we cannot divide by zero')
>>the try except concept
we cannot divide by zero
Here we are trying to overcome the zero division error which arises when any values divided by zero.
try:
a=[1,2,3]
print(a[5])
except error:
print("Exception handeled")
>> Exception handled without mentioning errors
2. Use of message in Try-Except block:
Example:
try:
print(1/0)
except ZeroDivisionError as ms:
print('error raised because:',ms)
>>error raised because: division by zero
3. Control flow Execution:
try:
statement -1
statement -2
except error:
statement-3
statement-4
>>
Case 1: No exception raised and program ran normal.
1,2,4 and normal
Case 2: The statement 1 raises exception and program runs normal.
3,4 and normal
Case 3: The statement 1 runs normally but statement 2 raises exception.
The except block has a error in the statement 3,so the program terminates
abnormally.
1 and abnormal
Case 4: The statement 1 raises exception. Statement 3 has some error, so the code
terminates abnormally
abnormal
4. Multiple Exceptional Block:
5. Single exceptional block that capture multiple exceptions
a=1,b=0
try:
print(a/b)
print("This won't be printed")
print('10+10')
except TypeError:
print("You added values of incompatible types")
except ZeroDivisionError:
print("You Divided by Zero")
>>You Divided by Zero
6. finally block:
Example:
try:
print(10/0)
except:
print(10/0)
finally:
print('i am final')
>>i am final
7. else block:
Example:
try:
print('10/0')
except:
print('i am except')
else:
print('hello python')
finally:
print('i am final')
>>10/0
hello python
i am final
8. Nested try except block:
Example:
try:
print("outer try block")
try:
print("Inner try block")
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
>>outer try block
Inner try block
Inner finally block
outer finally block
Comments
Post a Comment