Here in this blog, you will learn that how Python handles run time errors means exceptions? But before proceeding further lets laid down some focus on what is exception handling, why to use it and when an exception is raised.
When an error occurs during the execution of a program then it is known as exception. when any error occurs at run time, the exception is generated by Python to save the program from crash.
As run time errors terminate the program execution and abnormally shut down the software so it is must to caught run time errors for smooth execution of program or software.
Whenever in your code there is an error due unavailability of any resources , memory or misleading an exception is thrown by system, which has to be caught within the code to avoid shutdown of program.
By using the raise exception statement, you can easily raise an exception in your running program. By raising an exception, it breaks the current codes and returns the exception back till it get sorted.
IOError
If the file cannot be opened.
ImportError
If python cannot find the module
ValueError
Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value
KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)
EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data
If you find any suspicious code that can raise an exception, then you can protect your program by placing a suspicious code in a try: block. After this block, the except: statement handles the program in an efficient manner.
Syntax
try:
Perform your operations here;
......................
except Exception1:
jump in this section on a particular exception
except Exception2:
Jump in this section on a particular exception
else:
If there is no exception then execute this block.
Example:
try:
fh = open("test", "r")
fh.write("File Opened in try block!!")
except IOError:
print "Sorry Unable to open file or write"
else:
print "the content has been successfully written in the file"
The finally: block can be used along with try: block. In the finally: block you can put any code that you want must to be executed, whether the try: block raises an exception or not.
Example:-
try:
fh = open("test", "w")
fh.write("My test file to handle exception!!")
finally:
print "Error: Unable to open file or read data"