Even though a program is syntactically correct, it may throw errors at runtime and cause interruptions in the flow of the program. Such unusual conditions are called exceptions. For example, let’s try to divide a number by zero.
n = 100 m = 0 r = n/m print(r)
The program will print the following output:
Traceback (most recent call last): File "python-exceptions.py", line 3, inr = n/m ZeroDivisionError: division by zero
Here, we are trying to divide a number by zero and that results in an unusual condition. As a result, the Python program throws an exception called ZeroDivisionError.
Similarly, if we reach the end of the file and we try to perform some operations after that, the Python program will throw another exception called EOFError. These exceptions are built-in exceptions.
If a Python program throws an exception and we do not handle the exception, it will result in an error and termination of the program. But, Python provides us a way to handle the exceptions so that the program does not terminate abruptly, and instead, we can handle the unusual condition in our own way. The try and except statements in Python are used for this purpose.
If a Python statement can throw an exception, then we put the Python statement within a try clause. And, then, we use the …








































0 Comments