python


What is an Exception?

Exception are errors that occur at runtime .
In other words , if our program encounters an abnormal situation during it’s execution it raises an exception.
For example,the statement a=10/0 will generate an exception because Python has no way to solve division by 0

What Python does when an exception occurs?

Whenever an exception occurs , Python does 2 things :
1. It immediately terminates the code
2. It displays the error message related to the exception in a technical way Both the steps taken by Python cannot be considered user friendly because Even if a statement generates exception , still other parts of the program must get a chance to run
The error message must be simpler for the user to understand.
Example:


a=int(input("Enter first no:"))
b=int(input("Enter second no:"))
c=a/b
print("Div is",c)
d=a+b
print("Sum is",d)

Output:

Enter first no: 10
Enter second no: 5
Div is 2.0
Sum is 15
Output

Enter first no: 10
Enter second no: 0
Traceback (most recent call last):
  File "except1.py", line 3, in <module>
    c=a/b
ZeroDivisionError: division by zero
If we want our program to behave normally , even if an exception occurs , then we will have to apply Exception Handling
Exception handling is a mechanism which allows us to handle errors gracefully while the program is running instead of abruptly ending the program execution.

Exception Handling Keywords

Python provides 5 keywords to perform Exception Handling:

1.try
2.except
3.else
4.raise
5.finally
We will explore exception handling in detail in our next tutorial.