/    /  Python Handling Exceptions

Exception handling in Python

Exception means an error that occurs during the execution of a program. These exceptions terminate the current process and pass it to the calling process until it is handled. If these exceptions are not handled, the program will get crashed. They are convenient in many ways for handling errors and special conditions in the program. If we know that there could be an error, then we can make use of exceptions.

There are different types of errors that can be handled by using exceptions. By knowing them will make it easier to study about exception handling.

Import Error – This error occurs if python cannot find the module.

IO Error – This error happens if the file cannot be opened.

Value Error – This error is raised when a built-in function receives an argument that has the right type but an inappropriate value.

Keyboard Interrupt – This error occurs when the user hits interrupt key usually ctrl-c or delete.

EOF Error – It is raised when one of the built-in functions hits an end of file condition without reading any data.

In order to use exception handling in python, we need to know about keywords ‘try’ and ‘except’ which are used to catch exceptions.

The program within the try clause will be executed. If an exception occurs, the remaining code in try block will be skipped and except clause will be executed. The errors can be handled through the use of exceptions that are caught in try blocks and handled in except blocks.

We can also use finally block in addition to except block. This code will be executed regardless of an exception occurs.

Python Code:

while True:


x=int(input(“Enter the number : ”))
	except ValueError:
		print(“Not a Valid Number”)

In order to make the program produce an output of error when something goes wrong, python has many built-in exceptions.

To make it simple, if a code contains three functions a, b, c. if a calls b and b calls c, an exception occurs in c. If this exception cannot be handled by c, then it passes to b and then to a. if the error is not handled by any of the functions, then an error message is displayed.

In Python, a critical operation or function which can raise an exception is placed inside the try clause and the code which handles exceptions is written in except clause.

When an exception is raised in a python program, then it must either handle it immediately, or it terminates and quits the execution.